I had a question for my exam in which I didn't receive full points due to something I don't quite understand.
The question is the following:
Given the following program, apply changes that do not allow sum
to be printed as a negative number.
public class Summer {
private int sum;
public void up() {
sum++;
System.out.println(sum);
}
public void down() {
sum--;
System.out.println(sum);
}
}
the changes I made were the following:
public class Summer {
private volatile int sum;
public synchronized void up() {
sum++;
System.out.println(sum);
}
public synchronized void down() {
while (sum <= 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) { }
}
sum--;
System.out.println(sum);
}
}
The answer I got is that I cannot use sleep in this program, and I have to use wait and I must use function notifyAll to awake the Thread.
My question is, why is what I wrote wrong? shouldn't volatile not allow sum to get cached and therefore I always get the updated version of sum since there is no possible way I get a "dirty copy" and therefore there is no way to print a negative sum?