As a junior Java developer, while writing my first multi-threaded code, I remember wanting to use Thread.join(millis)
in a loop, and logging each time the thread was still alive. I was surprised to see that join
returns without letting me know the reason for returning, but considered it to be some kind of a native "magic" that a noob such as I was cannot understand.
Lately I had another look at java.lang.Thread
implementation, and as I was reading join
's implementation I was wondering again - since it merely waits on isAlive
condition, wouldn't it be natural to use the last state of the thread as the return value, so that client code does not have to check it explicitly outside?
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis
* the time to wait in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
I guess the answer might be a plain "Yes, it is possible, and you should ask the original JDK implementer.", but I am hoping for a more educating answer, if such one exists.