Skip to content

Instantly share code, notes, and snippets.

@sha1n
Last active December 19, 2022 05:47
Show Gist options
  • Save sha1n/9b6fc38bd48ea94eefaf9a4352eb4aad to your computer and use it in GitHub Desktop.
Save sha1n/9b6fc38bd48ea94eefaf9a4352eb4aad to your computer and use it in GitHub Desktop.
ExecutorService deadlocked nested tasks example
package com.example;
import lombok.val;
import java.util.concurrent.*;
public class ExecutorDeadLockExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
val executorService = Executors.newFixedThreadPool(1);
/*
* !!! THIS IS GOING TO BLOCK FOREVER !!!
* Because the executor service is fixed to a single thread and therefore there are no available threads to run
* nested tasks.
*/
System.out.printf("Example 1 returned: %d\n\n",
CompletableFuture.supplyAsync(() -> {
System.out.printf("1: %s\n", Thread.currentThread().getName());
return CompletableFuture.supplyAsync(() -> {
System.out.printf("2: %s\n", Thread.currentThread().getName());
return CompletableFuture.supplyAsync(() -> {
System.out.printf("3: %s\n", Thread.currentThread().getName());
return CompletableFuture.supplyAsync(() -> {
System.out.printf("4: %s\n", Thread.currentThread().getName());
return 1;
}, executorService).join();
}, executorService).join();
}, executorService).join();
}, executorService).join()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment