Can `LockSupport.park()` replace `Object.wait()`? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Can `LockSupport.park()` replace `Object.wait()`? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Currently I’m learning concurrency programming in Java. I notice LockSupport.park() introduced in Java 1.6 is much easier than Object.wait() to use, a typical usage of Object.wait() is like

// Thread1
synchronized (lock) {
    while (condition != true) {
        lock.wait()
    }

    // do stuff
}

// Thread2
synchronized (lock) {
    condition = true;
    lock.notify();
}

And I think I can rewrite it using LockSupport.park() like

// Thread1
while (condition != true) {
    LockSupport.park();
}

// do stuff

// Thread2
condition = true;
LockSupport.unpark(Thread1);

By using LockSupport.park(), tedious synchroinzed block disappears.

My question is, should I always prefer LockSupport.park() than Object.wait()? Is there any aspect that Object.wait() does better than LockSupport.park() such as performance?

Answer

The idea behind wait/notify is that the notifications are not thread-specific, the notifier doesn’t have to know the specific thread that needs notifying, it just tells the lock (or condition, for a ReentrantLock) that it’s notifying, and the lock and OS scheduler between them decide who gets the notification.

I would expect most of the time the notifier wouldn’t want to have to know what thread needs unparking so wait/notify would be a better choice for those cases. With park/unpark your code has to know more and there will be more opportunities for failure. You may think a synchronized block is tedious but what will really be tedious is sorting out cases where something doesn’t get unparked when it should have.

Note in your second example your condition needs to be volatile or Atomic or otherwise something where its updates are visible across threads.

We are here to answer your question about Can `LockSupport.park()` replace `Object.wait()`? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji