【发布时间】:2026-02-08 15:25:01
【问题描述】:
我想知道当我将 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();
}
使用sn-p:
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
}
【问题讨论】:
-
您应该为 C# 或 Java 或其他任何类型添加标签。
标签: java multithreading concurrency thread-local