Submitting to an Executor from a running task

前端 未结 3 1278
执念已碎
执念已碎 2021-01-17 02:03

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

3条回答
  •  情歌与酒
    2021-01-17 02:42

    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
    

提交回复
热议问题