【问题标题】:Java CachedThreadPool vs FixedThreadPool for multithreaded server用于多线程服务器的 Java CachedThreadPool 与 FixedThreadPool
【发布时间】:2019-06-03 22:52:26
【问题描述】:

我有一个服务器,它不断地监听客户端连接,并在每次客户端连接时创建一个新线程来处理该客户端的 I/O。现在,我有多个实现 Runnable 的类,并且在 run 方法中有一个 while 循环,该循环一直持续到客户端关闭。我创建了一个新的 Thread 对象并将 runnable 传递给该对象。我很确定还有其他更有效的方法可以做到这一点。我应该切换到 cachedThreadPool 还是 fixedThreadPool 或其他什么?

【问题讨论】:

标签: java multithreading executorservice


【解决方案1】:

如果未定义客户端的大小,我建议使用Executors#cachedThreadPool

文档Executors#cachedThreadPool:

* 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.

文档Executors#fixedThreadPool:

* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue.  At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.

因此,如果您不确定自己是否确实需要 5 个线程,则不应使用 Executors#fixedThreadPool

【讨论】:

  • 客户端处理线程可能长时间打开有什么问题吗?在 cachedThreadPool 的文档中说他们will typically improve the performance of programs that execute many short-lived asynchronous tasks.
  • Threads that have not been used for sixty seconds are terminated and removed from the cache. - 即使线程使用时间更长,也不应该成为问题。
猜你喜欢
  • 2015-12-23
  • 1970-01-01
  • 2013-07-31
  • 2010-09-24
  • 2019-05-27
  • 2015-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多