Java Concurrency and volatile
I came across an interesting behaviour of threads in James Roper’s Blog (http://jazzy.id.au/pebble/2009/04/24/java_concurrency_and_volatile.html). Tested it on Vista 64 bit machine and without a volatile keyboard, in my machine also the code goes into an infinite loop.
public class ThreadExperiement implements Runnable {
private volatile String str;
void setStr(String str)
{
this.str = str;
}
public void run()
{
while (str == null){}
System.out.println(str);
}
public static void main(String[] args) throws Exception
{
ThreadExperiement threadExp = new ThreadExperiement();
new Thread(threadExp).start();
Thread.sleep(1000);
threadExp.setStr("Hello world!!");
}
}
Put a print statement inside the while loop and it starts working. Strange , isn’t it?
Is it because of byte code optimisation which detects that there is nothing to do inside the loop ?

Leave a Reply