Let's say I have some resources that I want to synchronize access to. Most of these accesses are read only. I'd like to allow as many read only accesses at a time as the system can handle. But, I'd like the ability to stop the reading, make some writes, then allow reading again.
So the read threads might look like this
Resource r = null;
readLock.acquire();
r = resources.get();
readLock.release();
Any number of threads could do this at the same time, that wouldn't be a problem.
The write threads would look like this:
readLock.acquireOnlyMe(); // waits for all other threads to relase
// all other threads block when they try to acquire
r = resources.get();
r.setData(data);
readLock.release();
Right now, I'm using a ReentrantLock
that serves as both read and write. But obviously this is causing reads to work sequentially when I'd rather they work simultaneously.
What can I do to solve this problem?
It appears this is known as the readers-writers problem, and the wiki entry lists some C implementations, but none for Java.
Edit: I'm open to any Java library that will get the job done. The title says java.util.concurrent because it seems most likely that the answer will lie there.