[concurrency-interest] Re: synchronized vs ReentrantLock semantic

Gregg Wonderly gregg at cytetech.com
Tue Jun 14 09:36:32 EDT 2005


David Holmes wrote:
>>private Lock countLock = new ReentrantReadWriteLock();
>>private int count;
>>public int getCount() {
>>	Lock l = countLock.readLock();
>>	try {
>>		l.lock();
>>		return count;
>>	} finally {
>>		l.unlock();
>>	}
>>}
>>
>>public int addCount( int val ) {
>>	Lock l = countLock.writeLock();
>>	try {
>>		l.lock();
>>		count += val;
>>	} finally {
>>		l.unlock();
>>	}
>>}
> 
> 
> Aside: the lock() occurs before the try block, otherwise you may attempt to
> unlock a lock you never acquired.

Yes, typically, one should put the 'entry' event for anything undone in 
finally, outside of the try.  In this case, the only failure mode is 'l' 
being null which would also fail in 'finally' and not attempt anything 
ugly.  This is a good point to mention to people...

> I think you are misunderstanding the purpose of a ReadWriteLock. RWL allows
> for additional concurrency by allowing multiple concurrent readers. For that
> to actually occur "read" operations should be frequent and relatively
> lengthy compared to "write" operations that should be infrequent.

This is the point that I was trying to convince myself of.  I didn't 
express the concurrency that is not possible in my above example 
explicitly.  I was going back after the cache effects of synchronized. 
In my original misstatement I was drawing the wrong conclusions about 
the effects of read lock entry related to cache effects because I didn't 
remember what had to happen for read lock entry to work.

> Naively changing existing synchronized code to use a readLock for a "getter"
> method, and a writeLock for a "setter" method, will generally result in
> poorer performance due to the additional overhead of a ReadWriteLock.

Yes, there has to be a significantly larger percentage of read 
operations before you will see the effects of the concurrency benefits 
designed into the locks...

Gregg Wonderly


More information about the Concurrency-interest mailing list