How would I go about synchronization the actionListener and the main thread?
One way is to ensure all access to the variables in question is in synchronized methods/blocks (provided you sychronize on the same object).
Here is a simple program that, at least on my system, illustrates the surprising effects that lacking synchronisation can have:
public class Example
{
private int x;
private int y;
public /* * / synchronized / * */ int access() {
return x - y;
}
public /* * / synchronized / * */ void modify() {
++x;
++y;
}
public static void main(String[] args) {
final Example example = new Example();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
example.modify();
}
}
});
thread.start();
try {
for(int i = 0 ; i < 10 ; ++i) {
int difference = example.access();
System.out.println("Difference: " + difference);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
} finally {
System.exit(0);
}
}
}
One might naively expect that the two values will always be the same, so the difference should always be 0. A slightly less naive programmer might thing that the difference will always be 0 or 1, if the modifying thread is "between" incrementing X and Y.
Unfortunately, reality is much more complex. Without synchronisation, there are very few assumptions one can make about the output of this program. Without the synchronized blocks, here is sample output I got from running this program:
Difference: 0
Difference: -30
Difference: -12
Difference: -49
Difference: -60
Difference: -66
Difference: -37
Difference: -42
Difference: 0
Difference: -10
Quite surprising behaviour! This is known as a "race condition". Note the scary part: the result sometimes appears to be correct. It is possible to write code that looks like it works (under certain timing conditions), but may fail when those conditions change (like, when you release your application to the general public with faster or slower computers that you developed on).
However, removing the comments on both methods (thus ensuring that all access is correctly synchronized), gives us the "intended" output:
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
There are other ways to synchronize programs.
That said, it appears the first result I found via Google where the general "Java Timer" class, not the "Swing Timer". The latter runs on the "event dispatch thread", so it is possible that, depending on where your other accesses occur, all accesses are performed on the same thread. You should carefully check that this is the case - if so, you do not need to synchronize your code.