I have the code below
class VolatileCount {
volatile int count;
Object lock = new Object();
public void increment() {
synchronized (lock) {
count = count + 1;
}
System.out.print(" " + count);
}
}
If I call increment()on the same object from multiple threads, I get the following result (may differ on your computer)
2 3 2 5 4 8 8 6 11 13 10 9 15 14 12 20 19
Looking at the repeated numbers, which, it seems to me, happen, it seems that they are broken, because, looking at the first three numbers (2 3 2), if the stream sees 3, an increment occurs, and since the variable is variable, its value must be 3 or more, but cannot be 2 in any thread.
However, the print line seems to have been reordered here, is it right to reorder this line? What am I missing here? I am running JDK 7 (Eclipse)