I have a server that continually listens for client connections and creates a new thread each time a client connects to handle that client's I/O. Right now, I have multiple classes that implement Runnable and have a while loop in the run method that keeps going until the client is closed. I create a new Thread object and pass the runnable to that object. I'm pretty sure there are other, more efficient ways to do this. Should I switch to a cachedThreadPool or fixedThreadPool or something else?
Asked
Active
Viewed 435 times
1
-
Question duplicated https://stackoverflow.com/questions/17957382/fixedthreadpool-vs-cachedthreadpool-the-lesser-of-two-evils/ – Jonathan JOhx Jan 09 '19 at 08:07
1 Answers
4
I would recommend to use the Executors#cachedThreadPool
if the size of clients isn't defined.
Documentation 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.
Documentation 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.
So if you aren't sure that you exactly for example need 5 threads you shouldn't use the Executors#fixedThreadPool
.

CodeMatrix
- 2,124
- 1
- 18
- 30
-
Is there any problem with the fact that the client handling threads could be open for a long amount of time? In the documentation for cachedThreadPool it says that they `will typically improve the performance of programs that execute many short-lived asynchronous tasks.` – Caders117 Jan 09 '19 at 21:56
-
`Threads that have not been used for sixty seconds are terminated and removed from the cache.` - Even if a thread is longer used it shouldn't be a problem. – CodeMatrix Jan 10 '19 at 07:30