2 Replies Latest reply: Feb 26, 2012 5:17 AM by 850105 RSS

    Deadlock

    850105
      I am reading "Java concurrency in practice"

      On p168 it says "In a single threaded exectur, a task that submits another task to the exectur and waits for its result will always deadlock". It provides the following example:
          public static void main(String[] args) throws Exception {
              System.out.println("Main thread starting");
              new Deadlock2();
              System.out.println("Main thread ending");
          }
      
      class Deadlock2{
          private ExecutorService exec =  Executors.newSingleThreadExecutor();
      
          public Deadlock2() throws Exception{
              RenderPageTask rpt = new RenderPageTask();
              System.out.println("Result is "+rpt.call());
          }
      
          public class RenderPageTask implements Callable<String>{
      
              public String call() throws Exception {
                  Future<String> header,footer;
                  header = exec.submit(new LoadFileTask("header") );
                  footer = exec.submit(new LoadFileTask("footer"));
                  //String page = renderBody();
                  //will dealock here
                  return header.get() + " " + footer.get();
              }
          }
      
          public class LoadFileTask implements Callable<String>{
              private String s;
              public LoadFileTask(String s){
                  this.s = s;
              }
              public String call() throws Exception {
                   System.out.println("task " +s+ " starting");
                  return s + " done";
              }
      
          }
      }
      However this code is not deadlocking? The only difference between the example and the code above is that "String page = renderBody()" is commented out.

      Any ideas?

      Thanks
        • 1. Re: Deadlock
          jtahlborn
          that's not the only difference. your version does not use the executor for the "main" RenderPageTask, hence the lack of deadlock.

          i don't personally own the book, but i'd imagine you want something like:
              public Deadlock2() throws Exception{
                  RenderPageTask rpt = new RenderPageTask();
                  exec.submit(rpt);
              }
          • 2. Re: Deadlock
            850105
            Thanks jtahlborn, you were right. I created the constructor as it wasnt included in the book.

            But this makes much more sence now.