Friday, March 20, 2015

ReadWriteLock example in Java

One of the most significant improvements offered by locks is the ReadWriteLock interface and the ReentrantReadWriteLock class, the unique one that implements it. This class has two locks, one for read operations and one for write operations. There can be more than one thread using read operations simultaneously, but only one thread can be using write operations. When a thread is doing a write operation, there can't be any thread doing read operations.


In this article, you will learn how to use a ReadWriteLock interface implementing a program that uses it to control the access to an object that stores the prices of two books


BookInfo class




Create a class named Reader and specify that it implements the Runnable interface. This class implements a reader of the values of the BookInfo class attributes.



Create a class named Writer and specify that it implements the Runnable interface. This class implements a modifier of the values of the BookInfo class attributes.



Main class




As we mentioned previously, the ReentrantReadWriteLock class has two locks, one for read operations and one for write operations

The lock used in read operations is obtained with the readLock() method declared in the ReadWriteLock interface. This lock is an object that implements the Lock interface, so we can use the lock(), unlock(), and tryLock() methods. 

The lock used in write operations is obtained with the writeLock() method declared in the ReadWriteLock interface. This lock is an object that implements the Lock interface, so we can use the lock(), unlock(), and tryLock() methods.

It is the responsibility of the programmer to ensure the correct use of these locks, using them with the same purposes for which they were designed.When you get the read lock of a Lock interface, you can't modify the value of the variable. Otherwise, you probably will have inconsistency data errors.




If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

1 comment: