Is the interruption bit of a java.lang.Thread
guaranteed to be set, when a thread is interrupted after it was started (Thread#start() was called) but before it begins its execution (its run method is not yet called by the JVM)?
So that within the thread Thread.interrupted()
returns true
or a InterruptedException
is thrown when a method is called, that reacts to interruption in this way,
Or with an example:
Will the following snippet of Java code always, under any circumstances, print true
?
AtomicBoolean flag = new AtomicBoolean(false);
Thread thread = new Thread(() -> {
while (!flag.get()) {}
System.out.println(Thread.interrupted());
});
thread.start();
thread.interrupt();
flag.set(true);
The java-doc of java.lang.Thread#interrupt()
says:
Interrupting a thread that is not alive need not have any effect.
And the doc of java.lang.Thread#interrupted()
says:
A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.
My assumption is that alive
from these docs refers to the description in Thread#isAlive()
:
A thread is alive if it has been started and has not yet died.
From this, my answer would be yes. But I read in some sources that thread interruptions, which are done before the thread is running, are ignored. When I ran the code snippet it always printed true (but we know this isn't a guarantee in concurrent programming). Therefore I'm searching for clarification.