我的 ThreadLocal 始终包含并返回 null

000*_*000 1 java concurrency multithreading thread-local

我想知道当我将 threadlocal.set() 设置为 32 个元素的集合时,它是如何没有存储数据的。ThreadLocal.get() 总是返回 null;并且对应的 FutureTask 对象有一个结果属性 = NullPointerException。知道为什么 ThreadLocal 无法存储集合项吗?

public class MyCallable<T> implements Callable<Collection<T>> {

    public MyCallable( Collection<T> items ){
        tLocal = new ThreadLocal<Collection<T>>();
        tLocal.set( items );                    //SETS NULL ALTHOUGH the PARAMETER CONTAINS 32 ITEMS
    }

    @Override
    @SuppressWarnings("unchecked")
    public Collection<T> call() throws Exception {
        synchronized( lock ){
            ArrayList<T> _items = new ArrayList<T>();
            ArrayList<T> _e = ( ArrayList<T> ) tLocal.get();   //RETURNS NULL
            for( T item : _e ){
                _items = getPValue( item ));
            }
            return _items ;
        }
    }

    private ThreadLocal<Collection<T>> tLocal;

    private final Object lock = new Object();
}
Run Code Online (Sandbox Code Playgroud)

用法片段:

List<Future<Collection<T>>> futures = new ArrayList<Future<Collection<T>>>();
ExecutorService pool = Executors.newFixedThreadPool( 8 );

        for( int x = 0; x < numBatches; ++x ){
            List<T> items = retrieveNext32Items( x );
            futures.add( pool.submit( new MyCallable<T>( items ));
        }

        pool.shutdown();

        for( Future<Collection<T>> future : futures ) {
            _items.addAll( future.get() );                  //future.outcome = NullPointerException 
        }

        return _items
}
Run Code Online (Sandbox Code Playgroud)

wor*_*oru 5

您在主线程中创建 MyCallable 类型的对象,然后将它们提交到线程池。所以 MyCallable 的构造函数在一个线程中被调用,方法call在另一个线程中被调用。线程本地为每个线程保存一个单独的数据,所以难怪你会得到空值。

我不明白你为什么使用线程本地。items应该是 MyCallable 中的一个简单字段。如果您修改集合,最好将其复制到新集合中。