Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it deadlocking

Code from the book "Java Concurrency in Practice" Listing 8.1

Why is the code deadlocking? Is it because the rpt.call in main() is basically the same thread as that in Executors?

Even if I use 10 threads for exec = Executors.newFixedThreadPool(10); it still deadlocks?

public class ThreadDeadlock {
  ExecutorService exec = Executors.newSingleThreadExecutor();

  public class RenderPageTask implements Callable<String> {
    public String call() throws Exception {
        Future<String> header, footer;
        header = exec.submit(new LoadFileTask("header.html"));
        footer = exec.submit(new LoadFileTask("footer.html"));
        String page = renderBody();
        // Will deadlock -- task waiting for result of subtask
        return header.get() + page + footer.get();
    }
  }

   public static void main(String [] args ) throws Exception {

        ThreadDeadlock td = new ThreadDeadlock();
        ThreadDeadlock.RenderPageTask rpt = td.new RenderPageTask();
        rpt.call();
    }
}
like image 220
Lydon Ch Avatar asked Oct 12 '10 18:10

Lydon Ch


1 Answers

Your code doesn't deadlock - the following does:

public class ThreadDeadlock { 
    ...     
    public static void main(String [] args ) throws Exception { 
        ThreadDeadlock td = new ThreadDeadlock(); 
        ThreadDeadlock.RenderPageTask rpt = td.new RenderPageTask(); 

        Future<String> f = td.exec.submit(rpt);

        System.out.println(f.get());
        td.exec.shutdown();
    } 
}

This happens if you submit several simultaneous tasks to the single thread executor, when the first task is waiting for the result of the following ones. It doesn't deadlock with Executors.newFixedThreadPool(2) because LoadFileTasks are independent and can share one thread when another one is used by RenderPageTask.

The point of this example is that if you submit interdependent tasks to the ExecutorService, you should be sure that capacity of the thread pool is enough to execute them with the required level of parallelism.

like image 125
axtavt Avatar answered Oct 04 '22 11:10

axtavt