I have two methods read()
and write()
as below in a class.
class Store
{
public void write()
{
// write to store;
}
publi
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();
}
}
}