LockSupport parkUntil with blocker

Viewed 233

I am trying to understand what would be the purpose of a parameter for method: LockSupport::parkUntil. Let me give an example of what I mean here:

public static void main(String[] args) {

    Object blockedOn = new Object();
    System.out.println(blockedOn.hashCode());

    Thread parked = new Thread(() -> {
        System.out.println("parking the thread");

        long howMuch = System.currentTimeMillis() + 5 * 1000;

        while (System.currentTimeMillis() < howMuch) {
            LockSupport.parkUntil(blockedOn, howMuch);
        }

        System.out.println("parked the thread");
    });

    parked.start();
    sleepOneSecond();

    Object on = LockSupport.getBlocker(parked);
    System.out.println(on.hashCode());

}

private static void sleepOneSecond() {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

There are actually a few questions, if someone wants to help me understand this. First, is that while loop, I don't see any other means to get away from (documentation from LockSupport::parkUntil):

The call spuriously (that is, for no reason) returns.

So, I can only assume that LockSupport::parkUntil can fail, for no reason; as such I am forced to wrap this into a loop.

The next question I have is what would be the purpose of that blockedOn parameter? I do understand that when waiting long enough, I could do:

Object on = LockSupport.getBlocker(parked);

i.e.: find out the current state of the Object I am blocked on, and as such, somehow react to that. I was thinking I could interrupt the blocked thread (of course it has to support interruptions), but is there any other reason may be?

1 Answers

For your first question, this loop is the same you'd use for a Condition, ensuring that the "state predicate" is still satisfied when you exit the "parked" mode.

As for your second question, the blocker object is really only used for debugging purposes. The Javadoc states

The three forms of park each also support a blocker object parameter. This object is recorded while the thread is blocked to permit monitoring and diagnostic tools to identify the reasons that threads are blocked.

Note that the unpark method does not need the blocker object, suggesting that it isn't used as part of the parking mechanism (ie. unrelated to the permit). In fact, you can park multiple threads with the same blocker object.

Related