Javamex

Java discussion forum to accompany the Javamex web site.

The thread calling synchronzed(obj) acquires and owns that objects monitor till it releases it. Does lock.lock also behaves in a similar fashion. I tried calling lock.wait() after lock.lock() using an instance of ReentrantLock and the code gave me IllegalMonitorStateException.

Views: 145

Reply to This

Replies to This Discussion

Welcome to a slightly confusing feature of Locks.

If you use one of the explicit Lock classes such as ReentrantLock, then the method you call is called await()-- notice the "a" at the beginning-- rather than the wait() method (which still exists, as it does on any Java object, but is redundant on Locks).

Hi Neil,

Thanks for the quick reply. Maybe I was not very explicit in my message. I am made to understand that lock.lock behaves exactly the same as synchronized on the lock object. which means if synchronized acquires the object monitor, so does lock.lock. By that logic calling lock.wait should not throw IllegalMonitorStateException. But it seems like lock.lock and synchronized follows different logic to implement the same concept.

On finer levels, while going through the implementation of AQS I stumbled upon LockSupport.park method. Wondering if it uses the concept of monitor!

Thanks,

Pallav

Reply to Discussion

RSS

© 2024   Created by Neil Coffey.   Powered by

Badges  |  Report an Issue  |  Terms of Service