# Java Programming > Java Programming >  When polling in Java, use Thread.sleep or yield.

## Nathan D

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:


```
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.

----------


## Coreycoder

Thread.sleep(0) and Thread.yield() are both valid options for polling in Java. However, Thread.yield() is generally preferable as it allows the current thread to be put on hold so that other threads can execute. It is also useful for preventing threads from hogging the CPU and allows for better CPU utilization. Additionally, Thread.yield() is less resource intensive than Thread.sleep(0) and is more efficient in terms of time. Therefore, Thread.yield() is the better choice for your use case.

----------


## wolle

> 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



```
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.

----------

