记录不小心踩的一个坑newCachedThreadPool
问题描述,socket断开连接以后,后面再也连接不上了。
详情,我Executors.newCachedThreadPool();
创建线程池。
然后把Socket socket = serverSocket.accept();
所在的Runable给到了它执行。
开始没发现问题呀,正常的。
断开以后连接不上了,才去看代码,发现用了newCachedThreadPool。
那这个方法是怎么描述的呢?
/**
* Creates a thread pool that creates new threads as needed, but
* will reuse previously constructed threads when they are
* available. These pools will typically improve the performance
* of programs that execute many short-lived asynchronous tasks.
* Calls to {@code execute} will reuse previously constructed
* threads if available. If no existing thread is available, a new
* thread will be created and added to the pool. Threads that have
* not been used for sixty seconds are terminated and removed from
* the cache. Thus, a pool that remains idle for long enough will
* not consume any resources. Note that pools with similar
* properties but different details (for example, timeout parameters)
* may be created using {@link ThreadPoolExecutor} constructors.
*
* @return the newly created thread pool
*/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
重点:execute many short-lived asynchronous tasks.
所以sockert.appcet那个阻塞的,不适合。
就专门弄一个单一的线程给这个while(true)
问题应该是解决了。