Search code examples
javaconcurrencypolling

Thread.sleep or yield when polling in Java


I'm implementing a blocking file lock in Java, and when trying to acquire a lock I have a code block something like this:

while(!fileLockIsAcquired())
{
    Thread.sleep(100); //is this cool?
    tryAcquireFileLock();
}

That value of 100 milliseconds seems overly rigid to me, and I wonder if the scheduler couldn't be more intelligent if I used Thread.sleep(0) or Thread.yield(). Yield seems to me to communicate intent better, but I'm not sure that I fully understand how it is interpreted by the JVM. Is one option clearly better than the other?

The file is a remote file accessed through a webservice which has no blocking lock method, so I have to implement the blocking myself.


Solution

  • Using yield will make your polling rate much higher, which is probably not what you'd want. This is why I consider your current code as an acceptable first solution.

    On the other hand, you could make your Web service block (postpone its response until the lock is acquired) subject to a timeout. This would be a more solid solution since you could have both quick reaction once the lock is acquired, and a modest polling rate.