2

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.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • 1
    I believe [this](http://stackoverflow.com/a/6089967/248082) could be your answer. – nobeh Apr 10 '12 at 20:08
  • "the wiki entry lists some C implementations, but none for Java" -- what about the ReadWriteLock that it mentions was introduced in Java 5? – yshavit Apr 10 '12 at 20:14
  • That appears to be exactly what I'm looking for. I didn't realize there was a subpackage there. Excellent! – corsiKa Apr 10 '12 at 20:14
  • @yshavit Oh so it does. Wow, I feel like a real winner! – corsiKa Apr 10 '12 at 20:15
  • Btw, make sure you understand fairness -- it's very important in a read-write lock. You probably want the lock to be fair, or your writers could very easily get starved. – yshavit Apr 10 '12 at 20:16
  • Yeah my current implementation is fair, I would have my other one fair too. It really has to be fair, because the main writer is a daemon process. – corsiKa Apr 10 '12 at 20:17
  • @yshavit your first comment should be an answer – Jim Garrison Apr 11 '12 at 03:52

1 Answers1

2

If you wanted to limit the writer threads to one, then a ReentrantReadWriteLock would be your man.

For more than one - you probably want to lock your writers using a Semaphore. I recommend basing the initial permit count on the number of cores - probably cores+1.

Victor Grazi
  • 15,563
  • 14
  • 61
  • 94