Synchronizing data access with read/write locks
One of the most significant improvements offered by locks is the ReadWriteLock
interface and the ReentrantReadWriteLock
class, the unique class that implements that interface. 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 use write operations. If a thread is doing a write operation, other threads can't write or read.
In this recipe, you will learn how to use a ReadWriteLock
interface by implementing a program that uses it to control access to an object that stores the prices of two products.
Getting ready...
You should read the Synchronizing a block of code with a lock recipe to better understand this recipe.
How to do it...
Follow these steps to implement the example:
- Create a class named
PricesInfo
that stores information about the prices of two products:
public class PricesInfo {
- Declare two
double
attributes...