Reputation: 141
You have a storage object O.
Assume you have n reader methods and one writer method in a thread. If the writer method is called by a thread, none of the reader methods should be able to access O, but if a reader method accesses O, any other reader may access O but not the writer. Can I somehow implement this behaviour using "synchronized" statements in Java? If not: How else could I achieve this?
Thank you in advance.
Upvotes: 1
Views: 81
Reputation: 116938
You could use a ReadWriteLock
. You allocate it somewhere where the reader and writer threads can access it. Maybe pass it into their constructors.
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
Readers would do:
Lock lock = readWriteLock.readLock();
lock.lock();
try {
// do read operations here...
} finally {
lock.unlock();
}
Writers would do:
Lock lock = readWriteLock.writeLock();
lock.lock();
try {
// do write operations here...
} finally {
lock.unlock();
}
Upvotes: 7