Home » Core Java » util » concurrent » locks » ReentrantLock » Java ReentrantReadWriteLock Example

About Theodora Fragkouli

Theodora Fragkouli
Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.

Java ReentrantReadWriteLock Example

This is an example of how to make use of the ReentrantReadWriteLock class of Java. It is an implementation of ReadWriteLock, that also supports ReentrantLock functionality.

The ReadWriteLock is a pair of associated Locks, one for read-only operations and one for writing. Whereas, the ReentrantLock is a reentrant mutual exclusion Lock with the same behavior as the implicit monitor lock accessed using synchronized methods and statements, but with some more extended capabilities.

The ReentrantReadWriteLock is the mix of the above implementations. It does not have ordering preference between read and write, but may offer a fairness policy when needed.

In the example class below, we have created three Runnable implementations. They all use a ReentrantReadWriteLock lock variable. The lock is created using the ReentrantReadWriteLock(boolean fair) constructor, so it is given a fairness policy:

  • Read gets the lock. It uses the readLock() API method of ReentrantReadWriteLock to get a ReadLock. Then, it acquires the read lock, using the lock() method of ReadLock. While having the lock, it reads the value of a String message variable. Then it attempts to release the lock, using the unlock() method of ReadLock.
  • Both WriteA and WriteB also get the lock, using writeLock() method, that returns a WriteLock, and then using unlock() method of WriteLock. Since having the write lock, they both alter the value of the String message variable. Then, they release the write lock, using the unlock() method of WriteLock.

ReentrantReadWriteLockExample.java

package com.javacodegeeks.snippets.core;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockExample {

	private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);

	private static String message = "a";
	
	public static void main(String[] args) throws InterruptedException{
		Thread t1 = new Thread(new Read());
		Thread t2 = new Thread(new WriteA());
		Thread t3 = new Thread(new WriteB());
		t1.start();
		t2.start();
		t3.start();
		t1.join();
		t2.join();
		t3.join();
	}
	
	static class Read implements Runnable {

		public void run() {
			for(int i = 0; i<= 10; i ++) {
				if(lock.isWriteLocked()) {
					System.out.println("I'll take the lock from Write");
				}
				lock.readLock().lock();
				System.out.println("ReadThread " + Thread.currentThread().getId() + " ---> Message is " + message );
				lock.readLock().unlock();
				}
			}
		}
	
	static class WriteA implements Runnable {

		public void run() {
			for(int i = 0; i<= 10; i ++) {
				try {
					lock.writeLock().lock();
					message = message.concat("a");
				} finally {
					lock.writeLock().unlock();
				}
			}
			}
		}
	
	static class WriteB implements Runnable {

		public void run() {
			for(int i = 0; i<= 10; i ++) {
				try {
					lock.writeLock().lock();
					message = message.concat("b");
				} finally {
					lock.writeLock().unlock();
				}
			}
			}
		}
}

If you run the example, the result will be something like the one below:

ReadThread 9 ---> Message is a
ReadThread 9 ---> Message is aaba
ReadThread 9 ---> Message is aababa
ReadThread 9 ---> Message is aabababa
ReadThread 9 ---> Message is aababababa
ReadThread 9 ---> Message is aabababababa
ReadThread 9 ---> Message is aababababababa
ReadThread 9 ---> Message is aabababababababa
ReadThread 9 ---> Message is aababababababababa
ReadThread 9 ---> Message is aabababababababababa
ReadThread 9 ---> Message is aababababababababababa

Download the Eclipse Project

This was an example of ReentrantReadWriteLockExample class of Java.

Download
You can download the full source code of this example here: JavaReentrantReadWriteLockExample.zip
(+1 rating, 1 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of