开发者

Why is it deadlocking

开发者 https://www.devze.com 2023-01-19 13:52 出处:网络
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?

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();
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消