java method synchronization and read/write mutual exclusion
synchronized
is the simplest solution so you should explain what you mean by "doesn't seem like work for me" and perhaps show us how you used it.
The better solution is to use ReentrantReadWriteLock because it allows concurrent access to readers as well.
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();
}
}
}
When a method is synchronized on some object, a thread executing this method blocks all the other threads that try to enter another block/method that is synchronized on the same object.
So, if you want the writer threads to forbid any reader thread to read, you must synchronize both the write and the read method. There is no reason to synchronize on the Store
class. Synchronizing on the Store
object is more natural:
public synchronized void write() {
write to store;
}
public synchronized String read() {
read from store;
}
This, however, (maybe) has a drawback: it also forbids two reader threads to read at the same time. If you really need this to happen, you should use a ReadWriteLock. But this will lead to code that is less performant, and harder to understand and maintain. I would only use it if I have measured that this is needed.