gpt4 book ai didi

java - 为什么在使用单线程执行器时 "header.get() + footer.get()"会导致死锁?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:02 25 4
gpt4 key购买 nike

<分区>

这是 Java Concurrency In Practice 中的 list 8.1 :

public class ThreadDeadlock  {
ExecutorService exec = Executors.newSingleThreadExecutor();

public class RenderPageTask implements Callable<String> {
public String call() throws Exception {
Future<String> header, footer;
header = exec.submit(new LoadFileTask("header.html"));
footer = exec.submit(new LoadFileTask("footer.html"));
String page = renderBody();

//Will deadlock -- task waiting for result of subtask
return header.get() + page + footer.get();
}
}
}

它在

第 8 章:线程池> 第 8.1.1 节 线程饥饿死锁

并有标题:

"Task that deadlocks in a single-threaded Executor. Don't do this."

为什么会导致死锁?我认为 header.get() 被调用,然后 footer.get() 被调用,每个结果附加到字符串。为什么单线程执行器不足以一个接一个地运行它们?

相关章节正文:

8.1.1 Thread starvation deadlock

If tasks that depend on other tasks execute in a thread pool, they can deadlock. In a single-threaded executor, a task that submits another task to the same executor and waits for its result will always deadlock. The second task sits on the work queue until the first task completes, but the first will not complete because it is waiting for the resut of the second task. The same thing can happen in larger thread pools if all threads are executing tasks that are blocked waiting for other tasks still on the work queue. This is called thread starvation deadlock, and can occur whenever a pool task initiates an unbounded blocking wait for some resource or condition that can succeed only through the action of another pool task, such as waiting for the return value or side effect of another task, unless you can guarantee that the pool is large enough.

ThreadDeadlock in Listing 8.1 illustrates thread starvation deadldock. RenderPageTask submits two additional tasks to the Executor o fetch the page header and footer, renders the page body, waits for the results of the header and footer tasks, and then combines the header, body, and footer into the finished page. With a single-threaded executor, ThreadDeadlock will always deadlock. Similarly, tasks coordinating amongst themselves with a barrier could also cause thread starvation deadlock if the pool is not big enough.

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com