Search code examples
javajava.util.concurrent

A Question about LockSupport.getBlocker(Thread t) in Java


LockSupport.getBlocker(Thread t)

Returns the blocker object supplied to the most recent invocation of a park method that has not yet unblocked, or null if not blocked.

Why do the printouts in this code output different objects? Have I misunderstood LockSupport.getBlocker(Thread t)?


public static void main(String[] args) throws InterruptedException {
    Object lock = new Object();
    Thread t1 = new Thread(() -> {
        System.out.println("sub thread lock = " + lock);
        LockSupport.park(new Object());
    });
    t1.start();
    Thread.sleep(5000);
    Object getBlocker = LockSupport.getBlocker(t1);
    System.out.println("main thread blocker = " + getBlocker);
    System.out.println("is blocker same ? " + getBlocker == lock);
    LockSupport.unpark(t1);
    t1.join();
}

Output:

sub thread lock = java.lang.Object@6edf6345
main thread blocker = java.lang.Object@77459877
false

Solution

  • LockSupport.park(new Object());
    

    You're parking with a brand new object. Park with lock.

    LockSupport.park(lock);