8

I've written a simple application, which has main thread(producer) and multiple consumer threads. I want to broadcast a message from main thread, so all the consumer threads will receive it. However, I have troubles. I'm trying to understand how Thread.sleep may be related to Happens-Before. Here's my piece of code:

import java.util.*;

public class PubSub {

    public static void main(String[] args) {
        List<Consumer> consumers = new ArrayList<>();

        for (int i = 0; i < 3; i++ ) {
            Consumer consumer = new Consumer(
                    "Consumer"  + i
            );
            consumer.start();

            consumers.add(consumer);
        }

        Scanner scanner = new Scanner(System.in);

        while(true) {
            String message = scanner.nextLine();

            for (Consumer consumer: consumers) {
                consumer.notify(message);
            }

        }
    }

    static class Consumer extends Thread {

        private Queue<String> queue;

        public Consumer(String name) {
            super(name);
            this.queue = new LinkedList<>();
        }

        @Override
        public void run() {
            while(true) {

                if (!queue.isEmpty()) {
                    String message = queue.poll();

                    System.out.println(
                            getName() + ": Consuming message: " + message
                    );
                }
            }
        }

        public void notify(String message) {
            queue.add(message);
        }
    }

}

If I add sleep, the consumer will start receiving messages:

@Override
public void run() {
    while(true) {

        try {
            Thread.sleep(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (!queue.isEmpty()) {
            String message = queue.poll();

            System.out.println(
                    getName() + ": Consuming message: " + message
            );
        }
    }
}

Since Thread.sleep is a native method, I want to understand how it resolves happens-before.

I must note, that the true way of fixing happens-before is to make volatile keyword:

private volatile Queue<String> queue;

If you add synchronization onto the queue, it will also fix the issue:

@Override
public void run() {
    synchronized (queue) {
        while (true) {

            if (!queue.isEmpty()) {
                String message = queue.poll();

                System.out.println(
                        getName() + ": Consuming message: " + message
                );
            }
        }
    }
}
10
  • what do you think how they can be related?
    – hhafeez
    Feb 23, 2017 at 13:59
  • 1
    @hhafeez I don't know, that's why I'm asking.
    – Ivan Ursul
    Feb 23, 2017 at 14:08
  • When it doubt, consult the documentation. The Javadoc for thread.sleep() says nothing about "happens before" or "synchronization." I would therefore assume that there are no guarantees, and if I needed some form of synchronization, I would turn to some other mechanism to ensure it. Feb 23, 2017 at 14:29
  • What OS are you on? I'd guess Linux?
    – John Vint
    Feb 23, 2017 at 15:28
  • @JohnVint This is reproducible on Windows and Mac as well for me. Feb 23, 2017 at 15:31

4 Answers 4

2

I'm trying to understand how Thread.sleep may be related to Happens-Before

There is no relationship between happens-before and Thread.sleep. The JLS clearly specifies that Thread.sleep does not have any synchronization symantics :

Neither a sleep for a period of zero time nor a yield operation need have observable effects. It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to sleep or yield, nor does the compiler have to reload values cached in registers after a call to sleep or yield. For example, in the following (broken) code fragment, assume that this.done is a non-volatile boolean field:

while (!this.done) Thread.sleep(1000);

The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of this.done


On a related note, the consumer seems to start consuming messages (on my machine) if one adds statements that are evaluated at runtime right after the while loop. For example, the addition of this.toString() causes the consumer to start consuming messages.

public void run() {
    while(true) {
       this.toString();

This still does not explain the behavior but it further confirms that Thread.sleep is not necessarily the reason behind the Consumer suddenly seeing the updates made to the queue.

15
  • What I think is important is the sentence In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to sleep or yield, specifically it saying "does not have to". You are 100% right that it's not documented to require it, however, it does appear to be some ordering mechanism here, considering it seems to have the same effect as volatile.
    – John Vint
    Feb 23, 2017 at 15:45
  • My comment is more related to curiosity - in practice, is there actually some sync barrier?
    – John Vint
    Feb 23, 2017 at 15:45
  • @JohnVint I believe that statement probably means that there is no requirement that writes should always be flushed but it can happen under certain circumstances. I don't think it means that implementations are free to create a barrier when Thread.sleep is called. This is further confirmed by the preceding statement : It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. This feels like an affirmation rather than an option. That said, do you think this being enforced at a much deeper level than the runtime itself? Feb 23, 2017 at 16:01
  • It's certainly a fair point, but if there should be absolutely no synchronization semantics, why does include a Thread.sleep appear to have similar effects to a volatile read?
    – John Vint
    Feb 23, 2017 at 16:06
  • @JohnVint I have been playing around with this code for some time and the addition of statements that are evaluated at runtime (such as this.toString(); for example) right after the while loop in Consumer causes the consumer to start consuming messages. Addition of statements such as char s = "abc".charAt(1); on the other hand don't help the consumer to consume messages. I am starting to feel Thread.sleep has got nothing to do with this behavior. Feb 23, 2017 at 17:16
1

All indications of the code example above is that there is some kind of fence being issued. For example, if the queue is not volatile, the System.in will never trigger the Consumer once the Consumer is volatile, things would happen as they should. When issuing a sleep or yield, the app acts as if the queue were volatile.

Before reading the rest of my answer:

CKing's answer is the right one in terms of expectation. That is, no where in the JLS is it documented that there is any type of synchronization barrier when issuing a Thread.sleep or Thread.yield. One should NOT use Thread.sleep or Thread.yield as a synchronization point analogous to volatile as the underlying implementation can change for any release.

My suspicion

My answer from here on out was to satisfy my curiosity as to what is going on, and to do that I went into the native code for linux and Windows. You can find this snippet in src/os/linux/vm/os_linux.cpp.

A good chunk has been emitted to what I think is the relevant code

int os::sleep(Thread* thread, jlong millis, bool interruptible) {
  assert(thread == Thread::current(),  "thread consistency check");

  ParkEvent * const slp = thread->_SleepEvent ;
  slp->reset() ;
  OrderAccess::fence() ;

  if (interruptible) {
    jlong prevtime = javaTimeNanos();

    for (;;) {
      .... other code ...

      prevtime = newtime;

      {
        assert(thread->is_Java_thread(), "sanity check");
        JavaThread *jt = (JavaThread *) thread;
        ThreadBlockInVM tbivm(jt);
        OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);

        jt->set_suspend_equivalent();
        // cleared by handle_special_suspend_equivalent_condition() or
        // java_suspend_self() via check_and_wait_while_suspended()

        slp->park(millis);

        // were we externally suspended while we were waiting?
        jt->check_and_wait_while_suspended();
      }
    }
  ... other code ...

It's issuing a fence and eventually suspending the thread. I believe this is the relevant information to tell us what is happening and why we see similar behaviors to volatile.

Note: This doesn't happen only because of a native call. You can invoke Thread.currentThread() which is also native but see behaviors as if it were not volatile.

0

This particular program has nothing to do with sleep or even synchronization. I just proved that it works without sleep and synchronization too. if you notice there is nothing to synchronize here as there are no shared variables. I think it's just a timing thing in that there is no guarantee what moment a particular thread will execute a particular line of code in its run method. I just put a for loop after while for (int i = 0; i < 1000; i++){} and without sleep or synchronize it started to print values in que. I am even able to print messages with out introduction of for loop if I debug the code. updated method

public void run()
    {
        while (true)
        {
            for (int i = 0; i < 1000; i++)
            {

            }


            if (!queue.isEmpty())
            {
                String message = queue.poll();

                System.out.println(getName() + ": Consuming message: " + message);
            }
        }

update: So after doing some more analysis of the code, it turns out the OP was somehow right asking relationship. https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html Defining volatile, does establish happened-before relationship. which guarantees that other threads can see the update. Note here that we are updating the consumer in main thread and child thread has its own copy of variables and child thread does see the update in consumer if que is volatile Now come to second part, JVM does some optimization and reordering (which is upredictable) behind the scene by looking at the nature of code. when we introduce some code or statement like for loop or thread.sleep the compiler decides differently and it might say lets get the updated variable while executing this line and that's why we see the messages coming after introducing some statements after the while loop. I checked updating the consumer in child thread and its work fine (prints messages correcly) without volatile synchronization,sleep or any dummy line of code we injected after while.

8
  • Debugging may introduce memory barriers. I don't think it's timing. It does a busy spin checking the existence of data. And when data is successfully added into the queue, nothing gets printed (ie: the consuming thread never polls it from the queue). Adding volatile resolves this. It appears to be a classic compiler ordering issue.
    – John Vint
    Feb 23, 2017 at 16:23
  • I agree but how would you explain when it works with introduction of for loop like this
    – hhafeez
    Feb 23, 2017 at 16:25
  • I tried introducing the for loop and couldn't recreate it. Can you post the code in more detail and I will try that?
    – John Vint
    Feb 23, 2017 at 16:28
  • it does not work for smaller loops but the value like 1000 has caused some timing delay
    – hhafeez
    Feb 23, 2017 at 16:32
  • This still does not answer why either thread sleep or volatile appears to be working Feb 23, 2017 at 16:47
-1

Looks like it is typical issue with visibility of shared object. You add to queue from main thread, but read it from another one. There is nothing here related to Thread.sleep()

3
  • Then why does declaring the queue volatile allow it to function correctly? Thread.sleep appears to have similar effects.
    – John Vint
    Feb 23, 2017 at 15:52
  • Result of volatile is that consumer thread will see last version queue. Feb 23, 2017 at 16:11
  • My question is why does it successfully log, if Thread.yield() or Thread.sleep(0) is introduced before the read, similar to if the queue is volatile
    – John Vint
    Feb 23, 2017 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.