我想知道当我将它设置为 32 个元素的集合时,threadlocal.set() 是如何没有存储数据的。 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();
}
用法片段:
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
}
最佳答案
您在主线程中创建类型为 MyCallable 的对象,然后将它们提交到线程池。因此,在一个线程中调用 MyCallable 的构造函数,在另一个线程中调用 call
方法。 Thread local 为每个线程保留一个单独的数据,所以难怪你会得到空值。
我不明白你为什么使用本地线程。 items
应该是 MyCallable 中的一个简单字段。如果您修改集合,也许最好将其复制到新集合。
关于java - 我的 ThreadLocal 始终包含并返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31958871/