Is thread starvation deadlock happening here in the code?

后端 未结 3 2180
孤城傲影
孤城傲影 2020-12-30 17:37
//code taken from java concurrency in practice

  package net.jcip.examples;

import java.util.concurrent.*;


public class ThreadDeadlock
       {
    ExecutorServi         


        
3条回答
  •  既然无缘
    2020-12-30 17:51

    Deadlock & Starvation is occurring at following line:

    return header.get() + page + footer.get();
    

    HOW?
    It will happen if we add some extra code to the program. It might be this one:

        public void startThreadDeadlock() throws Exception
        {
            Future  wholePage = exec.submit(new RenderPageTask());
            System.out.println("Content of whole page is " + wholePage.get());
        }
        public static void main(String[] st)throws Exception
        {
            ThreadDeadLock tdl = new ThreadDeadLock();
            tdl.startThreadDeadLock();
        }
    

    Steps that leading to deadLock:

    1. Task is submitted to exec for Rendering the page via Callable implemented class RenderPageTask.
    2. exec started the RenderPageTask in separate Thread , the only Thread that would execute other tasks submitted to exec sequentially .
    3. Inside call() method of RenderPageTask two more tasks are submitted to exec . First is LoadFileTask("header.html") and second is LoadFileTask("footer.html"). But since the the ExecutorService exec obtained via code Executors.newSingleThreadExecutor(); as mentioned here uses a single worker thread operating off an unbounded queueThread and the thread is already allocated to RenderPageTask , So LoadFileTask("header.html") and LoadFileTask("footer.html") will be en queued to the unbounded queue waiting for there turn to be executed by that Thread.
    4. RenderPageTask is returning a String containing the concatenation of output of LoadFileTask("header.html") , body of page and output of LoadFileTask("footer.html"). Out of these three parts page is obtained successfully by RenderPageTask . But other two parts can only be obtained after both tasks are executed by the single Thread allocated by ExecutorService . And Thread will be free only after call() method of RenderPageTask returns . But call method of RenderPageTask will return only after LoadFileTask("header.html") and LoadFileTask("footer.html") is returned. So Not letting LoadFileTask to execute is leading to Starvation . And each task waiting for other task for completion is leading to DeadLock

      I hope this makes clear of why thread starvation deadlock is occurring in above code.

提交回复
热议问题