Can I create multiple thread pools (ExecutorService)?

I created several instances of ExecutorService in my code, usually on each page of the user interface there is one instance of ExecutorService. Each instance of the ExecutorService will execute some HTTP request request flows.

private ExecutorService m_threadPool = Executors.newCachedThreadPool(); 

Can this be done?

The problem I ran into is that sometimes the HTTP request gets a -1 response code from the HttpURLConnection getResponseCode () call. I do not know if this is caused by multiple instances of threadpool.

Thanks.

+4
source share
2 answers

ExecutorService itself is another object, so there is no big overhead. But each thread pool has unused threads by default, and this is the reason for the large resource. I would suggest setting the default number of pre-generated threads for each pool (1 or 0 if you are not sure if any requests have been sent) in order to reduce the cost of creating additional objects. Themes will be created on demand and you can keep your code clean.

Another solution is to use a single thread pool, but to maintain a separate task list for each user interface window. In this case, when the window closes, you will have to iterate through all the tasks and manually cancel the launch (this can also be done in a separate thread). The task can be represented by Future Future<?> (It has convenient methods isDone() and cancel() ).

+3
source

This should not be called by thread pool instances. However, I would say that having multiple thread pools is questionable. Why do you need this? This can lead to many unnecessary threads, and therefore unnecessary memory usage.

+1
source

Source: https://habr.com/ru/post/1311812/


All Articles