what is wrong with volatile variables?
Guys,
What is wrong with snippet below? Why both conditions sometimes are true at the same time:
if ( fine != suspect ) {
if ( fine == suspect ) {
Why foobar is printed out? I had a long time arguments, but failed to prove anything. Could you help me please? What do you think?
Code:
public class VWC {
private volatile boolean suspect;
private boolean fine;
private boolean anotherFine;
private Object lock = new Object();
private int failures;
private int iterations;
private VWC() {
new Thread() {
public void run() {
while( true ) {
synchronized( lock ) {
try {
lock.wait();
} catch ( Exception exception ) {
}
}
synchronized( lock ) {
if ( fine != suspect ) {
System.err.println( "foo" );
if ( fine == suspect ) {
System.err.println( "bar" );
}
}
if ( fine != anotherFine ) {
System.err.println( "baz" );
}
}
}
}
}.start();
}
private void run() {
while( true ) {
synchronized( lock ) {
++iterations;
fine = ! fine;
anotherFine = ! anotherFine;
}
suspect = ! suspect;
synchronized( lock ) {
lock.notify();
}
}
}
public static void main(String[] args) {
new VWC().run();
}
}