//code taken from java concurrency in practice
package net.jcip.examples;
import java.util.concurrent.*;
public class ThreadDeadlock
{
ExecutorService exec = Executors.newSingleThreadExecutor();
public class LoadFileTask implements Callable<String> {
private final String fileName;
public LoadFileTask(String fileName) {
this.fileName = fileName;
}
public String call() throws Exception {
// Here's where we would actually read the file
return "";
}
}
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();
}
}
}
This code is take from Java concurrency in practice and as per the authors “ThreadStarvtionDeadlock” is happening here. Please help me finding how ThreadStarvationDeadlock is happening here and where? Thanks in advance.
Deadlock & Starvation is occurring at following line:
HOW?
It will happen if we add some extra code to the program. It might be this one:
Steps that leading to deadLock:
execfor Rendering the page viaCallableimplemented classRenderPageTask.execstarted theRenderPageTaskin separateThread, the onlyThreadthat would execute other tasks submitted toexecsequentially .call()method ofRenderPageTasktwo more tasks are submitted toexec. First isLoadFileTask("header.html")and second isLoadFileTask("footer.html"). But since the the ExecutorServiceexecobtained via codeExecutors.newSingleThreadExecutor();as mentioned here uses a single worker thread operating off an unbounded queueThread and the thread is already allocated to RenderPageTask , SoLoadFileTask("header.html")andLoadFileTask("footer.html")will be en queued to the unbounded queue waiting for there turn to be executed by thatThread.RenderPageTaskis returning a String containing the concatenation of output ofLoadFileTask("header.html"), body of page and output ofLoadFileTask("footer.html"). Out of these three partspageis obtained successfully byRenderPageTask. But other two parts can only be obtained after both tasks are executed by the single Thread allocated byExecutorService. And Thread will be free only aftercall()method ofRenderPageTaskreturns . Butcallmethod ofRenderPageTaskwill return only afterLoadFileTask("header.html")andLoadFileTask("footer.html")is returned. So Not lettingLoadFileTaskto execute is leading to Starvation . And each task waiting for other task for completion is leading to DeadLockI hope this makes clear of why thread starvation deadlock is occurring in above code.