unable to synchronize on primitive wrapper class?
Hi all,
My colleague and I found this while debugging our program. We created a
simple program to duplicate the issue. So here's the program:
public class VolatileVar {
static class Worker implements Runnable {
public static Integer total = 0;
public static Object dummy = new Object();
public int count = 0;
public void run() {
while (!Thread.interrupted()) {
synchronized (total) {
total++;
}
count++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Worker w1 = new Worker(), w2 = new Worker();
Thread t1, t2;
t1 = new Thread(w1); t1.start();
t2 = new Thread(w2); t2.start();
Thread.sleep(1000);
t1.interrupt();
t2.interrupt();
Thread.sleep(50);
System.out.println(t1 + ".count=" + w1.count + "\n" +
t2 + ".count=" + w2.count + "\n" +
"total="+ Worker.total + "\n" +
"DIFF=" + (w1.count+w2.count-Worker.total));
}
}
Don't you think the total should equals to the sum of two individual
counts? Well, it doesn't. I tried all the type decorator (volative,
final, etc) but none of them helped.
Finally we tried to create another object (dummy) and synchronized on
that. Amazingly enough that worked. So there seems to be some issue on
synchronization on primitive wrapper class and somehow JRE treat wrapper
class and normal classes differently. If that's really the case, that
is a bug. I wonder if anyone else sees this or have it been reported to
Java development team.
Regards/Eniac