Is it safe for a task (a Runnable) being run by an Executor to submit (execute()) a task? Can it result in deadlock, if using any of the standard Java executors
If you call get on the future then you can surely deadlock, in simple example as below this might be obvious to spot but if you have some class hierarchy that hides executors usage then someone by mistake can introduce such bug.
class TestApp {
public static class MyCallable
implements Callable {
public Integer call() throws ExecutionException, InterruptedException {
Future future = pool.submit(new MyCallable());
System.out.println("MyCallable: before get 2");
future.get(); // deadlocks here
System.out.println("MyCallable: after get 2");
return 0;
}
}
static ExecutorService pool = Executors.newSingleThreadExecutor();
public static void main(String [] args) throws ExecutionException, InterruptedException {
Future future = pool.submit(new MyCallable());
System.out.println("MyCallable: before get 1");
future.get();
System.out.println("MyCallable: after get 1");
}
}
prints
MyCallable: before get 1
MyCallable: before get 2
MyCallable: before get 2
MyCallable: before get 2