Just checked in an improvement for JDBM at google code (we are using jdbm here for a little job), applying a pattern for handling thread contention that I worked out a while ago. Didn’t have the source, but I remembered how it worked. I think I’m getting old, you know – recognising problems as something that I encountered ages ago in another context.
I any case, the particular specific fun bit is LockingStrategy.java.
Basically – we have a “thing” and it’s mostly threadsafe. For certain operations (we’ll call ’em reads): go for it. Threads won’t interfere and we want them to be able to run freely. But certain other operations need exclusive access to the thing – all other threads must block.
The problem is that things that need exclusive access can’t just wait for no-one to be reading. Like one of those people that can’t merge onto a freeway, they’d wait forever. The reading threads have to stop and wait when something needs exclusive access. Thus, although readers run freely with respect to one another, they cant do so with respect to threads that exclusively lock.
Potentially, multiple threads might want exclusive access. They have to run one at a time.
And finally – I don’t want things to poll. Polling is bad. Everything must wait() and be notify()ed.
The key to the algorithm is the use of two java mutexes, not one. One regulates the readers, and one regulates the exclusive lockers. The interplay between the two, however, is … a bit of a headspin. But it does work.