views:

125

answers:

1

Code from Java concurrency in practice book 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 thread 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();
}

}
+3  A: 

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.

axtavt