Site Search:

ThreadDeadlock.java

Back>

import java.util.concurrent.*;

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

    public class LoadFileTask implements Callable<String> {
        private final String fileName;

        public LoadFileTask(String fileName) {
            this.fileName = fileName;
        }

        public String call() throws Exception {
            // Here's where we would actually read the file
            return fileName;
        }
    }

    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
            System.out.println("thread starvation deadlock below");
            return header.get() + page + footer.get();
        }

        private String renderBody() {
            // Here's where we would actually render the page
            return "body";
        }
    }
    
    public static void main(String...args) {
        ThreadDeadlock threadDeadlock = new ThreadDeadlock();
        try {
            Future<String> result = threadDeadlock.exec.submit(threadDeadlock.new RenderPageTask());
            System.out.println(result.get());
            threadDeadlock.exec.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

The above example illustrate thread starvation deadlock. The single threaded Executor only have one thread. However, the worker threads submitted 2 additional tasks to the Executor asking for the rendering of header and footer, then block waiting for the result. Since all the worker thread (1 thread) is exausted, the two additional tasks will never get chance to run, the program will deadlock.