Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java method synchronization and read/write mutual exclusion

Tags:

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.

like image 632
vijayashankard Avatar asked Apr 29 '12 13:04

vijayashankard


People also ask

What is mutual exclusive synchronization in Java?

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.

Why wait () notify () and notifyAll () methods have to be called from a synchronized method or block?

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 ...

What is synchronization method in Java?

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.


1 Answers

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();        }     } } 
like image 69
Tudor Avatar answered Nov 18 '22 12:11

Tudor