Consider the following code:
// Below block executed by thread t1
synchronized(obj) {
obj.wait(0);
}
// This block executed by thread t2
synchronized(obj) {
obj.notify();
}
I understand that in above code if t1 has taken ownership of synchronized block and at the same time if thread t2 tries to take synchronized block, then t2 goes for a kernel wait.
I want to avoid this situation and spin t2 before the block until t1 calls wait and leaves ownership of the block. Is that possible?
The JVM need not implement entry to a locked synchronized block as a hard block and context switch. It has the option of using lighter weight methods, such as spin locks. In fact, the Oracle JVM goes to some lengths to avoid blocking. So you might find that the JVM has already done this optimisation for you. And if it has not, that might be because the JVM has evidence that a spin lock would be a bad idea.
Yes, it's possible to do what you want.
An implementation of the interface java.util.concurrent.locks.Lock (such as ReentrantLock) allows you to busy-wait for a lock using the tryLock method (invoked from a loop).
To implement wait and notify functionality, you call the method newCondition on Lock to obtain a Condition object. The Condition interface has the methods await and signal/signalAll that work analogous to wait and notify/notifyAll.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With