CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2022
    Urbana, Illinios

    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:
        Thread.sleep(100); //is this cool?
    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

  2. #2
    Join Date
    Oct 2022

    Re: When polling in Java, use Thread.sleep or yield.

    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.

  3. #3
    Join Date
    Feb 2017

    Re: When polling in Java, use Thread.sleep or yield.

    Quote Originally Posted by Nathan D View Post
    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) {
        if (fileLockIsAcquired()) break;
        if (yield_count++ < 5  {
        } else {
           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

Click Here to Expand Forum to Full Width