从正在运行的任务提交给执行者 [英] Submitting to an Executor from a running task

查看:86
本文介绍了从正在运行的任务提交给执行者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Runnable )是否安全? /api/java/util/concurrent/Executor.htmlrel =nofollow> 执行者 提交( execute() )一项任务?如果使用任何标准Java执行程序,是否会导致死锁?我应该使用任何特定的配置,或者如果我想防止死锁,请避免使用标准执行程序?我猜测将任务提交给不同的执行者是安全的,但是如何将任务提交给执行原始任务的执行者呢?

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? Is there any particular configuration I should use, or avoid, if I want to prevent deadlock, for the standard executors? I'm guessing that submitting a task to a different executor is safe, but what about submitting the task to the executor running the original task?

推荐答案

如果你打电话获取未来那么你肯定会陷入僵局,简单的例子如下所示,这可能是显而易见的,但是如果你有一些隐藏执行者使用的类层次结构那么就是错误的可以引入这样的bug。

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<Integer> 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<Integer> future = pool.submit(new MyCallable());
        System.out.println("MyCallable: before get 1");
        future.get();
        System.out.println("MyCallable: after get 1");
    }
}

打印

MyCallable: before get 1
MyCallable: before get 2
MyCallable: before get 2
MyCallable: before get 2

这篇关于从正在运行的任务提交给执行者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆