-
December 6th, 2022, 07:24 AM
#1
When polling in Java, use Thread.sleep or yield.
In Java, I'm developing a blocking file lock, and while attempting to acquire a lock, I have a code block that looks like this:
Code:
while(!fileLockIsAcquired())
{
Thread.sleep(100); //is this cool?
tryAcquireFileLock();
}
That figure of 100 milliseconds seems very stiff to me, and I'm wondering if the scheduler couldn't be more clever if I used Thread.sleep(0) or Thread.yield() instead. Yield appears to express purpose more effectively, although I'm not sure I really understand how the JVM interprets it. Also, I tried reading similar online articles but they didn't assist me well. Is one choice plainly superior to the other?
Because the file is a remote file accessible via a web service that lacks a blocking lock mechanism, I must implement the blocking myself.
Last edited by 2kaud; December 17th, 2022 at 07:09 AM.
Reason: Web site removed
-
December 17th, 2022, 03:31 AM
#2
Re: When polling in Java, use Thread.sleep or yield.
 Originally Posted by Nathan D
Because the file is a remote file
Maybe the idea is not to hog the remote connection with frequent lock requests. A compromise would be to send a couple of quick requests and, if unsuccessful, wait a little longer, like
Code:
int yield_count = 0;
while (true) {
tryAcquireFileLock();
if (fileLockIsAcquired()) break;
if (yield_count++ < 5 {
Thread.yield();
} else {
Thread.sleep(100);
yield_count = 0;
}
}
I would also put in another counter to ensure the lock-acquiring process does not go on forever. It will hang your code.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|