Unsafe: removing the monitorEnter/monitorExit/tryMonitorEnter methods

David M. Lloyd david.lloyd at redhat.com
Tue Mar 4 15:32:56 UTC 2014

On 03/03/2014 09:45 PM, David Holmes wrote:
> On 3/03/2014 10:56 PM, David M. Lloyd wrote:
>> Yes, that would necessarily be the contract of a Monitors class, just as
>> it is part of the contract of Lock today.  If your argument is that it
>> shouldn't be allowed because it might be used wrong, we might as well
>> just delete most of the JDK, ReentrantLock included, since it suffers
>> from the exact same potential problem.  The difference is that monitors
>> have a simple API in the form of synchronized that people were in the
>> past and would continue to be free (and recommended) to use.
> We should not introduce anything that allows something that was
> guaranteed to be safe by the language, to become unsafe.

Define 'safe'.  Because I don't think it's unsafe, any more than 
unpaired lock/unlock are.  There is no uninitialized memory being 
accessed, no way to bypass security checks, no way to manipulate memory 
directly, etc.  I find this argument to be particularly weak without 
specific cases.  As far as I can tell, the language doesn't make it 
safe, it makes it *convenient*, and that's a big distinction.

There are two cases I can see that are potentially problematic: extra 
acquires, and extra releases.

The risk of extra acquires is that the thread might exit while still 
holding the lock, leaving it locked forever.  However, just parking a 
thread indefinitely (via various means) within a synchronized block is 
equally unsafe.

The risk of extra releases is that you'll hit IllegalMonitorState 
exceptions and thread-safety/publication problems.  But a user can make 
this same mistake today with locks.  The difference is, that in most 
cases people would choose the convenience of synchronized unless there 
is a specific reason for it, making this problem far less likely than 
the corresponding locks case.


More information about the core-libs-dev mailing list