In my project, on a security system, I was using a socket to get the details of the client and then store it in a database (his IP and port he connected from and service he accessed). I was wondering if the fetching of the details and storing them in a database should be done in separate threads or a single thread. Which is the more advantageous approach?
Quick answer: Is the main socket handler multi-threaded? If not, then definitely hand the processing of the request off to a thread pool executor. If the request handler is already multi-threaded, then it’s more of a judgement call (…or a performance enhancement to be borne out with load testing).
…
If the service isn’t handling requests with a pool of execution threads, then it probably should. That’s a more central issue than getting the client details asynchronously.
The main benefit of using a separate thread is to do the work asynchronously — that is, in the background while the main thread moves on to the next request. If the fetch will be slow and potentially block handling of incoming requests, then handing off the fetch to a separate thread would be a good idea.
However, if the app already handles requests with a pool of execution threads, and the number of threads is large enough, a separate thread pool might not bring much benefit.
Note: DO NOT spin up a new thread for each request. Instead, look in the currency package for ThreadPoolExecutor
or an ExecutorService
.
Here’s a sample link (the first one in the search) from a quick lookup of ThreadPoolExecutor
: http://www.javacodegeeks.com/2011/12/using-threadpoolexecutor-to-parallelize.html.