• Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple Race condition

 
Prateek Pune Agrawal
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Trying to understand simple race condition problems in Java.
Created a simple program to figure out the behavior.

package net.jcip.examples;

public class MyThreadObject{

public boolean flag;

public MyThreadObject(boolean flag) {
super();
this.flag = flag;
}

public boolean isFlag() {
return flag;
}

public void setFlag(boolean flag) {
this.flag = flag;
}

public static void main(String[] args) throws InterruptedException {
MyThreadObject threadObject=new MyThreadObject(false);
MyThread thread=new MyThread(threadObject);
thread.start();
Thread.sleep(10000);
threadObject.setFlag(true);
System.out.println("flag set to true");
System.out.println("exitng main");
}

}
class MyThread extends Thread{

MyThreadObject object;

public MyThread(MyThreadObject object) {
super();
this.object = object;
}
@Override
public void run() {
System.out.println("In run flag "+object.isFlag());
while (!object.flag) {
// System.out.println("");

}
System.out.println("Exiting the thread");
}

}

If i uncomment the Sysout in run method MyThread terminates as soon as the value of flag is set to true.
What i think MyThread should not see the updated value of flag without proper synchronization in MyObject
 
Henry Wong
author
Sheriff
Posts: 22528
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prateek Pune Agrawal wrote:
If i uncomment the Sysout in run method MyThread terminates as soon as the value of flag is set to true.
What i think MyThread should not see the updated value of flag without proper synchronization in MyObject


Race conditions causes unknown stuff to happen -- there is no guarantee on what will happen. Or in other words, what is supposed to happen is undefined. Just because, "with proper synchronization", the updated value is always seen, it doesn't mean that the opposite is true. Meaning, without synchronization, the updated value is not seen. This is simply not true.

Anyway, what could be happening is... with the system out method calls, it is causing the JVM to flush any temporary variables, in order to have the register free for the method. Of course, this may not be the case, after all, it is a race condition, and whose behavior is undefined.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!