The following are two methods on an object I’ve created. The superclass has implemented MouseListener.
@Override public void mousePressed(MouseEvent event){
mIsPushed = true;
System.out.println("Button pushed");
}
@Override public void mouseReleased(MouseEvent event){
mIsPushed = false;
System.out.println("Button released");
}
When the two System.out.println calls are uncommented, the program works fine and behaves as it should. When they aren’t, it does nothing. I have even placed breakpoints at the mIsPushed assignments and they’re never reached.
However, if I put a breakpoint at the point where these two functions are called, the debugger reaches it and the calls are made.
Can anyone tell me what I’ve missed?
This is probably due to the different threads caching their own values of the
mIsPushedvariable.You need to synchronize the access to this variable. You have a few different options:
volatilejava.util.concurrentpackage (such asAtomicBoolean)synchronizedkeyword.In more detail: The Java memory model does not guarantee that a read of a variable from one thread will yield the last value written to that variable from another thread. This is to allow a JVM to optimize the execution of a Java program. Adding a
System.out.printlnmay flush the cache and cause a new value to be loaded when needed.To explicitly tell the JVM to make sure that no cached value should be used, you need to introduce a “happens before”-relation between the write and the read.
Further reading: