Tuesday, April 29, 2008

Compiler Optimization Can cause problem

Last week, I was created a presentation on Multi-threading in Java. Though this fact, I have covered in presentation but still wanted to blog on same. In multi-threading world, compiler optimization can cause serious problems. Just check my small code:

public class NonVolatileProblem extends Thread{

ChangeFlag cf;

public static void main(String[] args) {
ChangeFlag cf = new ChangeFlag();
NonVolatileProblem th1 = new NonVolatileProblem(cf);
NonVolatileProblem th2 = new NonVolatileProblem(cf);

th1.start();
th2.start();

}
public void run() {
cf.method1();
cf.method2();
}

public NonVolatileProblem(ChangeFlag cf) {
this.cf = cf;
}
}

class ChangeFlag {

boolean flag = false;

public void method1() {
flag = false;
try {
Thread.sleep(1000);
} catch(Exception e) { System.out.println("Don't want to be here"); }
if(flag) {
System.out.println("This can be reached ");
}
System.out.println("Value of flag" + flag);
}

public void method2() {
flag = true;
}
}

Check out the reason in bold. Now if compiler optimize the code and remove the part of if(flag), thinking of that flag value will always be false. Then we have a situation here(FBI style of speaking :-D), because other thread can change its value and can make the flag value true. Just run this code 5-6 may be 10 times, you will be able to see the SOP statement "This can be reached". Just for the shake of getting that I have added sleep statement. Here what I got on my 3rd run of the code :)

Value of flag:false
This can be reached
Value of flag:true

Handling such type of situation is not difficult, specification says to add a word volatile before the variable flag which will tell the compiler not to optimize its code just by seeing some initial value or declaration.

1 comment:

123 123 said...

Interesting article as for me. It would be great to read a bit more about that theme. Thnx for posting that information.
Sexy Lady
UK escort