How to avoid deadlocks and using too many threads?

Using Executors.newFixedThreadPool(int nThreads) is a good way to minimize the overhead of creating too many threads, but it can lead to a deadlock if all threads are waiting for another job that is waiting for a thread to wait from the pool. Sometimes a problem can be solved using several thread pools, but sometimes it is not possible. I am looking for something similar to newFixedThreadPool , except when all empty threads are blocked - in this case the pool should grow, despite the predefined boundary. Is there something like this?


Actually, the dead end is not so important here. The real problem is how to "manage the number of running threads", and not their total number. It can also be interesting when trying to fully use the processor without creating an unnecessary number of threads.

+4
source share
3 answers

If you have a contentious issue, this is a design issue. If you want to quickly fix it, as you described, you will only treat the symptoms, not the underlying illness.

Instead, you should reorganize your project to eliminate the deadlock using other means.

+4
source

It is usually a bad idea for threads in the pool to block while waiting for other threads in the same thread pool.

I would try to change the design to non-blocking. If a thread needs the result of another operation processed by the same executor, I would ask that the executor return the task after the completion of the second operation. Or put the object in the queue that needs to be picked up later when another task ends.

Alternatively, you can do what Swing does with modal dialogs, and have a thread that is going to block the start of the child thread to handle requests until the parent thread is blocked. This is difficult to do correctly, and you will need to manually manage streams that are much less secure than using the Contractor.

+2
source

Executor.newCachedThreadPool(); The cached thread pool will check if there are any threads available. If there is, the thread pool will use the thread. If this is not the case, the thread pool will create a new thread. The lifetime for life is 60 seconds, so after 60 seconds additional threads will be completed.

+1
source

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


All Articles