0%

Thread pool self-induced deadlocks

1
2
3
4
5
6
7
8
9
10
final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> {
System.out.println("First");
try {
executorService.submit(() -> System.out.println("Second")).get();
} catch (final InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("Three");
});

Deadlock! Step by step:

  • Task printing "First" is submitted to an idle single-threaded pool
  • This task begins execution and prints "First"
  • We submit an inner task printing "Second" to a thread pool
  • The inner task lands in a pending task queue - no threads are available since the only one is currently being occupied
  • We block waiting for the result of the inner task. Unfortunately while waiting for the inner task we hold the only available thread
  • get() will wait forever, unable to acquire thread
  • Deadlock