Logowww.asingh.netHomeNewsBioInterestsTechnicalSearchContact
 

Implementing Read-Write Locks in Java

There can be many interesting situations when separate, concurrently running threads need to share data. A commonly given example to explain such a situation is the producer/consumer problem. Another common example is of Airline-Ticketing stations.

Consider multiple ticketing stations for the same flight, all of them should be able to read the data concurrently, but only one of them should be able to change the status of a 'seat ' at a given time. This requires Read-Write locks.

Read-write lock allows multiple threads to acquire a read lock provided no other thread currently has a write lock on the same object. A thread can acquire a write lock if no other thread owns either a read lock or a write lock.

Java does not provide a ready-made solution for Read-Write Locks. Therefore we will implement a class that provides the aforesaid functionality. Consider a class RWLock, whose objects will provide the functionality of Read-Write locks.

Following is the source code for class RWClass. For simplicity, try, catch blocks etc have been omitted. Real working code is available for download.


class RWLock
{
	private int givenLocks;
	private int waitingWriters;
	private in waitingReaders;
	private Object mutex;
	:
	:
	public void getReadLock()
	{
		synchronized(mutex)
		{
			while((givenLocks == -1) || 
				   (waitingWriters != 0))
			{
				mutex.wait();
			}

			givenLocks++;

		}
	}
	
	public void getWriteLock()
	{
		synchronized(mutex)
		{
			waitingWriters++;

			while(givenLocks != 0)
			{
				mutex.wait();
			}

			waitingWriters--;
			givenLocks = -1;
		}
	}

	public void releaseLock();
	{
		synchronized(mutex)
		{

			if(givenLocks == 0)
				return;
		
			if(givenLocks == -1)
				givenLocks = 0;
			else
				givenLocks--;

			mutex.notifyAll();
		}
	}

}

Variable RWlock.givenLocks represents the number of threads holding the read lock; it will be -1 if there is a write lock and zero if no thread is holding the lock. Variable mutex is used to synchronize access to the RWLock object.

Methods getReadLock() and getWriteLock() will return immediately with a lock or else block the calling thread until the lock is available. Our implementation of RWLock class will give preference to the waiting writer threads over the readers, through the variable RWLock.waitingWriters. That means if we have two threads waiting to acquire the lock, the one waiting for write lock will get the lock first. You can modify the code to give preference to readers also.

Sample output of a small program, that tests RWLock, is also provided in the download. It shows how other threads wait for the lock when one thread has a write lock and how the writer gets prefrence when the lock becomes available.

 

| Home | News | Bio | Interests | Technical | Search | Contact |