Unsafe: removing the monitorEnter/monitorExit/tryMonitorEnter methods

Dr Heinz M. Kabutz heinz at javaspecialists.eu
Sun Mar 2 08:51:51 UTC 2014


With a curious 9 months old crawling around the house, I've just moved 
the sharp knives to the top draw in the kitchen - out of reach.  I don't 
think we should be encouraging people to use monitor.tryLock() for 
various reasons:

1. We have a richer interface with Lock/ReentrantLock, including better 
Condition that allow easier timed wait idioms.

2. It is just too easy to get the idioms wrong for Lock.lock() and 
Lock.unlock().  Every time I show this idiom some people in the audience 
start arguing with me:

lock.lock();
try {
  // do something
} finally {
  lock.unlock();
}

IMHO, this is really an edge case that might be useful to have 
semi-accessible at some point, but not something that should generally 
be done.  It belongs in the same draw as the sharp knives and the 
ability to cause arbitrary asynchronous exceptions (which has been made 
more difficult to do in Java 8).

Brian Goetz wrote:
> Except that Lock has features that are not supported by intrinsic 
> locks (timed wait, interruptible wait.)  So the Lock returned would 
> not conform to Lock's contract, and attempting to call these methods 
> would probably throw UOE.
>
> On 2/27/2014 6:12 AM, Stephen Colebourne wrote:
>> On 26 February 2014 20:54, Martin Buchholz <martinrb at google.com> wrote:
>>> It does seem that being able to tell whether a java object monitor is
>>> currently locked is useful for debugging and monitoring - there 
>>> should be a
>>> way to do that.
>>
>> Perhaps it would be useful to be able to expose a java object monitor
>> as an instance of Lock?
>>
>> Lock lk = Lock.ofMonitor(object)
>> if (lk.tryLock()) {
>>    ...
>> }
>>
>> Such a method feels like it would be a useful missing link between
>> synchronized and locks.
>>
>> Stephen
>>
>



More information about the core-libs-dev mailing list