I have two methods read()
and write()
as below in a class.
class Store { public void write() { // write to store; } public string read() { // read from store; } }
1) The Store
object is a singleton.
2) I have a Writer
class which will write to the store and several Reader
classes which will read from the store at the same time.
My requirement is that when the writer is writing to the store, all the readers should wait. i.e., when control is in write()
, all the calls to read()
should be blocked. How do I achieve this? I have tried synchronize(Store.class)
in the write()
method, but doesn't seem like work for me.
Mutually exclusive synchronization helps threads to communicate while sharing common data. That can happen in Java by one of the three ways, with the use of a synchronized block, static synchronization and a synchronized method.
Calling notify() or notifyAll() methods issues a notification to a single or multiple threads that a condition has changed and once the notification thread leaves the synchronized block, all the threads which are waiting for fight for object lock on which they are waiting and lucky thread returns from wait() method ...
Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.
The best option in this case is to use a reader-writer lock: ReadWriteLock. It allows a single writer, but multiple concurrent readers, so it's the most efficient mechanism for this type of scenario.
Some sample code:
class Store { private ReadWriteLock rwlock = new ReentrantReadWriteLock(); public void write() { rwlock.writeLock().lock(); try { write to store; } finally { rwlock.writeLock().unlock(); } } public String read() { rwlock.readLock().lock(); try { read from store; } finally { rwlock.readLock().unlock(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With