Is there a cheap way to wait and wake threads in Java?

20 hours ago 1
ARTICLE AD BOX

I am working on a concurrent problem where the critical section is not contested because every thread needs to have a go at some shared resource, but because some thread must, and there can be only one. Put simply, threads are happy to wait for anyone to finish the job, because (other than the cost of context switching) it does not slow them down, as otherwise they would have to do it themselves. This is not a once and done scenario; threads may require different 'levels of completion' of continuous work.

The classic Java way of solving such a problem would be to acquire an object lock with sychronized, check the state of protected variables, and go to sleep with wait unless satisfied. Then, the thread doing the actual work periodically calls notifyAll to let them know about the progress being done. This is however not ideal, because each notified thread will sequentially need to acquire the lock and check the condition, even when they could all be awakened at once and do a volatile read of a variable completely concurrently.

A second, somewhat related problem is that the cost of parking a thread is significant; are there lock implementations which optimistically try to spin lock for a bit in hopes that the resource will soon be available, before resorting to sleeping?

Read Entire Article