Submitting to an Executor from a running task

前端 未结 3 1240
执念已碎
执念已碎 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:46

    Is it safe for a task (a Runnable) being run by an Executor to submit (execute()) a task?

    Provided it doesn't create too many tasks as to overload the system, it is safe. e.g. if you have a task which creates two tasks and they create two tasks ...

    Can it result in deadlock, if using any of the standard Java executors?

    The Executors are thread safe and the task is added to a queue.

    Is there any particular configuration I should use, or avoid, if I want to prevent deadlock, for the standard executors?

    You can create a ThreadPoolExecutor with one thread and a SynchronousQueue and this could block itself. But I wouldn't do that. ;)

    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?

    Provided you have any of the following, you won't have problem. Often you have all of these

    • a growing queue
    • the execute fail if it cannot be added i.e. don't block
    • an expandable thread pool

提交回复
热议问题