Reputation: 9023
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.
Upvotes: 2
Views: 1352
Reputation: 200206
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.
Upvotes: 3
Reputation: 68715
I believe wait is a better choice than anything else, the reason being because other thread can notify when it releases the lock. Advantage with wait is that it will immediately come out once notified but sleep will not.
Upvotes: 0