For example take this code snippet,
static volatile boolean isDone = false;
public static void main(String[] args) throws InterruptedException {
// I know ArrayBlockingQueue cannot take 0 as the constructor arg, but please for the sake of example, let's pretend this was legal
final ExecutorService exec = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(0));
exec.execute(() -> {
isDone = true;
// does the compiler add a return statement here?
});
while (!isDone){
}
try {
exec.execute(() -> {});
} catch (RejectedExecutionException e) {
System.out.println("What if this might actually happen in a super bad timing by the scheduler??");
}
exec.shutdown();
}
It might seem like the case that the first Thread created by the ExecutorService is dead, but is that really the case?
In the Thread Api https://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html it says that if the run() method returns then the Thread is dead, but I don't explicitly call a return and I'm not sure what the Runtime or the compiler actually does.
For example it might implicitly add a return statement after isDone = true and before the enclosing } such as
exec.execute(() -> {
isDone = true;
return;
});
However, there might be some delay before actually hitting the return, since this is up to the scheduler and so the the next submitted runnable to the executor might get Rejected if the scheduler decided not to run that return statement before doing exec.execute(() -> {}); in the try block.