5

In the following code, if i use sysout statement inside for loop then the code executes and goes inside the loop after the condition met but if i do not use sysout statement inside loop then then infinite loop goes on without entering inside the if condition even if the if condition is satisfied.. can anyone please help me to find out the exact reason for this. Just A sysout statement make the if condition to become true. why is it so?

The code is as follows:-

class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;

   RunnableDemo( String name){
       threadName = name;
       System.out.println("Creating " +  threadName );
   }
   public void run() {
      System.out.println("Running " +  threadName );
       for(;;)
       {
           //Output 1: without this sysout statement.
           //Output 2: After uncommenting this sysout statement
           //System.out.println(Thread.currentThread().isInterrupted());
           if(TestThread.i>3)
           {
               try {
                   for(int j = 4; j > 0; j--) {
                       System.out.println("Thread: " + threadName + ", " + j);
                   }
               } catch (Exception e) {
                   System.out.println("Thread " +  threadName + " interrupted.");
               }
               System.out.println("Thread " +  threadName + " exiting.");
           }
       }
   }
   
   public void start ()
   {
      System.out.println("Starting " +  threadName );
      if (t == null)
      {
         t = new Thread (this, threadName);
         t.start ();
      }
      
   }

}

public class TestThread {
       static int i=0;
   public static void main(String args[]) {
   
       RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
      try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        
        e.printStackTrace();
    }
     
    i+=4;
     System.out.println(i);
   }   
}

Output without sysout statement in the infinite loop:-

Output with sysout statement in the infinite loop:-

dev.doc
  • 569
  • 3
  • 12
  • 18
Meenakshi Kumari
  • 120
  • 1
  • 11
  • 2
    Im gonna guess you are running into volatile issues. Try making static int i=0; static volatile int i =0; If the behavior is now the same ill put up an answer with an explanation. – Henk De Boer Jan 07 '16 at 13:17
  • @Aaron Its an infinite loop, so they keep executing it constantly, right...? EDIT: Aaron left the building. – Henk De Boer Jan 07 '16 at 13:19
  • 1
    @Henk de Boer, I tried using volatile and it is working fine. But can you explain what changes does the sysout statement makes which let the code to work even without using volatile keyword. – Meenakshi Kumari Jan 07 '16 at 13:33

2 Answers2

3

The problem here can be fixed by changing

static int i=0;

to

static volatile int i=0;

Making a variable volatile has a number of complex consequences and I am not an expert at this. So, I'll try to explain how I think about it.

The variable i lives in your main memory, your RAM. But RAM is slow, so your processor copies it to the faster (and smaller) memory: the cache. Multiple caches in fact, but thats irrelevant.

But when two threads on two different processors put their values in different caches, what happens when the value changes? Well, if thread 1 changes the value in cache 1, thread 2 still uses the old value from cache 2. Unless we tell both threads that this variable i might be changing at any time as if it were magic. That's what the volatile keyword does.

So why does it work with the print statement? Well, the print statement invokes a lot of code behind the scenes. Some of this code most likely contains a synchronized block or another volatile variable, which (by accident) also refreshes the value of i in both caches. (Thanks to Marco13 for pointing this out).

Next time you try to access i, you get the updated value!

PS: I'm saying RAM here, but its probably the closest shared memory between the two threads, which could be a cache if they are hyperthreaded for instance.

This is a great explanation too (with pictures!):

http://tutorials.jenkov.com/java-concurrency/volatile.html

Henk De Boer
  • 373
  • 2
  • 6
  • One more thing i want to ask, if i use thread.sleep instead of sysout statement, even then also the if condition becomes true. Does Thread.sleep also take some memory and flush away data from cache? – Meenakshi Kumari Jan 08 '16 at 04:27
  • @Marco13 Ok, I will adapt the answer. Thanks for the correction! – Henk De Boer Jan 08 '16 at 12:09
  • @MeenakshiKumari Best way to find out is to test it yourself! :) But no, I wouldn't think so, unless (once again by accident) some foreign piece of code triggers a cache clear while the sleep is running. Like I said, I'm not an expert and threading is often much more complicated in practice than it seems. So I am hesitant to give you very concrete rules here, sorry. The sleeping itself is just telling the OS that you don't have anything to do for now, nothing more, so you shouldn't rely on it having any special properties like flushing the memory. – Henk De Boer Jan 08 '16 at 12:18
  • 1
    @ Henk De Boer, yes, actually i tried using different piece of code before the infinite loop and found that if some code which needs some memory is written there then only in that case the if condition becomes true. Thanks for your response. – Meenakshi Kumari Jan 08 '16 at 12:38
2

When you are accessing a variable value, the changes aren't written to (or loaded from) the actual memory location every time. The value can be loaded into a CPU register, or cached, and sit there until the caches are flushed. Moreover, because TestThread.i is not modified inside the loop at all, the optimizer might decide to just replace it with a check before the loop, and get rid of the if statement entirely (I do not think it is actually happening in your case, but the point is that it might).

The instruction that makes the thread to flush its caches and synchronize them with the current contents of physical memory is called memory barrier. There are two ways in Java to force a memory barrier: enter or exit a synchronized block or access a volatile variable. When either of those events happens, the cached are flushed, and the thread is guaranteed to both see an up-to-date view of the memory contents, and have all the changes it has made locally committed to memory.

So, as suggested in comments, if your declare TestThread.i as volatile, the problem will go away, because whenever the value is modified, the change will be committed immediately, and the optimizer will know not to optimizer,e the check away from the loop, and not to cache the value.

Now, why does adding a print statement changes the behaviour? Well, there is a lot of synchronization going on inside the io, the thread hits a memory barrier somewhere, and loads the fresh value. This is just a coincidence.

Dima
  • 39,570
  • 6
  • 44
  • 70
  • I'm not saying you're wrong, but is the optimizer allowed to make such heavy assumptions about member variables? Seems error prone. – Henk De Boer Jan 07 '16 at 13:54
  • Sure, why not? If there is no memory barrier inside the loop, and a variable is not modified by the current thread, it is perfectly safe to assume that it remains constant. In fact, making this assumption is safer than not making it, because it makes the behavior deterministic. – Dima Jan 07 '16 at 14:07
  • Yeah but how does it know at compile time that the value of i will not change before the thread is spawned? maybe im missing something. – Henk De Boer Jan 07 '16 at 14:10
  • @HenkDeBoer it does not need to know at compile time. I am saying it could rewrite the function like this: `if(TestThread.i > 3) for(;;) { stuff } else for(;;);` – Dima Jan 07 '16 at 14:28
  • Ah ok, so it can just look ahead when executing? cool. – Henk De Boer Jan 07 '16 at 14:30