[concurrency-interest] Re: synchronized vs ReentrantLock semantic

David Holmes dholmes at dltech.com.au
Tue Jun 14 00:58:00 EDT 2005


Gregg,

> private Object countLock = new Object();
> private int count;
> public int getCount() {
> 	synchronized( countLock ) {
> 		return count;
> 	}
> }
> public int addCount( int val ) {
> 	synchronized( countLock ) {
> 		count += val;
> 	}
> }
>
> is the same thing as doing
>
> 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.

> which, in and of itself doesn't look very exciting as a replacement.

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.

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.

Cheers,
David Holmes



More information about the Concurrency-interest mailing list