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