Unsafe: removing the monitorEnter/monitorExit/tryMonitorEnter methods

David M. Lloyd david.lloyd at redhat.com
Sun Mar 2 16:58:31 UTC 2014


Making the language Kindergarten-friendly at the cost of general 
usefulness is a mistake, IMO.  And anyway there's nothing that is less 
safe about a Monitors class than ReentrantLock; on the other hand, 
monitors continue to be considerably lighter (size and (for most of the 
history of JUC) speed) by every measurement I've ever made.  I would 
advise monitors over ReentrantLock 9 times out of 10 in any of our code.

I just don't think your metaphors - neither of monitor methods being 
dangerous, nor of Java developers being infants - are really apt.

On 03/02/2014 02:51 AM, Dr Heinz M. Kabutz wrote:
> 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
>>>
>>


-- 
- DML



More information about the core-libs-dev mailing list