Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay in running thread due to system.out.println statement [duplicate]

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:-

like image 992
Meenakshi Kumari Avatar asked Jan 07 '16 13:01

Meenakshi Kumari


1 Answers

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

like image 151
Henk De Boer Avatar answered Sep 30 '22 15:09

Henk De Boer