Unexpectedly, the thread was starved to death!

When building a thread pool, we can build a thread pool for a single thread and a thread pool for multiple threads.

So is it possible to deadlock if the thread pool is not used properly? We know that deadlock is caused by circular competition for resources. Threads in the thread pool are also a kind of resources, so deadlock may occur if the threads in the thread pool are scrambled.

In the thread pool of a single thread, if an executing thread uses the thread pool to submit the second task, because there is only one thread in the thread pool, the second task will wait for the execution of the first task to release the thread, and the first task is waiting for the execution of the second task to complete the task. This creates a thread starvation deadlock

Thread starvation deadlock does not necessarily occur in the thread pool of a single thread. This problem may occur as long as the thread pool is recycled.

Let's look at the following example:

public class ThreadPoolDeadlock {

    ExecutorService executorService= Executors.newSingleThreadExecutor();

    public class RenderPageTask implements Callable<String> {
        public String call() throws Exception{
            Future<String> header, footer;
            header= executorService.submit(()->{
                return "header";
            });
            footer= executorService.submit(()->{
                return "footer";
            });
            return header.get()+ footer.get();
        }
    }

    public void submitTask(){
        executorService.submit(new RenderPageTask());
    }
}

We submitted a renderpagetask in the executorservice, and renderpagetask submitted two tasks. Because the executorservice thread pool has only one thread, a deadlock will occur.

Our thread is starving!

For examples of this article, please refer to https://github.com/ddean2009/learn-java-concurrency/tree/master/ThreadPoolDeadlock

For more information, please visit flybean's blog

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>