我使用了这样的线程池:new ThreadPoolExecutor(8, 8, 8, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(2048));
运行它并并行提交任务一段时间,然后使用FutureTask
结果get
。一开始看起来很正常,但是池的8个线程很快就全部变成了WAITING(停车)状态。没有任何一个线程可以再次运行,任务队列变得越来越长。我看了FutureTask.awaitDone()
一下,我想可能是最后一行代码LockSupport.park(this)
导致了这种状态。那么,我应该怎么做才能避免这些线程的状态呢?
实际代码(基于SpringBoot的项目):
public class MyAsyncConfigurerSupport extends AsyncConfigurerSupport {
@Bean
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(8);
executor.setKeepAliveSeconds(8);
executor.setQueueCapacity(2048);
executor.setAllowCoreThreadTimeOut(true);
executor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor exe) -> {
throw new RuntimeException("TooBusy");
});
return executor;
}
}
public class MyController {
@Autowired
private MyService service;
public String get(String key) {
Future<String> future = service.getSomeThing(key);
// numbers of same kind of futures
return future.get();
}
}
@Service
public class MyService {
@Async
public Future<String> getSomeThing(String key) {
// Call remote http server
String result = feignClient.callAPI(key);
return new AsyncResult<>(result);
}
}