First, a really dumb question, I was just wondering what the waiting \'parking\' means ? Is the thread waiting to be parked or is it just been parked and therefore is in wai
The part that made me revisit this question that I could not get around while reading the documentation, was:
If the permit is available then it is consumed and the call returns immediately...
So when the permit is "available", who and how makes it available, so that it could get consumed immediately? This was somehow trivial to find out:
public static void main(String[] args) {
Thread parkingThread = new Thread(() -> {
System.out.println("Will go to sleep...");
sleepTwoSeconds();
System.out.println("Parking...");
// this call will return immediately since we have called LockSupport::unpark
// before this method is getting called, making the permit available
LockSupport.park();
System.out.println("After parking...");
});
parkingThread.start();
// hopefully this 1 second is enough for "parkingThread" to start
// _before_ we call un-park
sleepOneSecond();
System.out.println("Un-parking...");
// making the permit available while the thread is running and has not yet
// taken this permit, thus "LockSupport.park" will return immediately
LockSupport.unpark(parkingThread);
}
private static void sleepTwoSeconds() {
try {
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void sleepOneSecond() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
The code speaks for itself, the thread is running but not yet called LockSupport.park, while some other thread calls LockSupport.unpark on it - thus making the permit available. After that we call LockSupport.park and that returns immediately since the permit is available.
Once you think about it, this is a bit dangerous, if you expose your threads to some code you do not control and that code calls LockSupport.unpark while you park after that - it might not work.