Reputation: 764
I have two threads updating a shared int
at the same time. Most of times, this code will print 0
and 1
. But some times, it will print 0
and 0
(one update failed). If I make the int value
volatile
, will fix that update fail, once for all?
This is not a Home-Work question, really. I just wrote these code and this question, like if was, to clarify my understanding of Java Memory Model. I read this Article.
I know this code will be fixed in a synchronized
way, but this is not the scope of question, is just about the volatile will fix or not, and why.
public class Testes{
public static int value = 0;
public static void main(String ... args) {
T t = new T();
T t2 = new T();
t.start();
t2.start();
}
}
class T extends Thread{
public void update(){
System.out.println(Testes.value++);
}
public void run(){
this.update();
}
}
Upvotes: 1
Views: 72
Reputation: 342
Thanks to John for clarifying the same...
When you execute System.out.println(Testes.value++) what happens is it is a postfix operation for increment...so the println is done first and then value gets incremented...thats why you see 0 by the first thread..but after the println is done its execution the value is now 1 ..that is why the second thread shows 1 when it prints the value ....
Upvotes: 0
Reputation: 40256
If I make the int value volatile, will fix that update fail, once for all?
No. The issue you are seeing is almost certainly not related to memory inconsistency. The failure is because of atomicity. It is widely known ++
operator is not atomic (it is actually three operations). There is plenty of information you can read on about it.
Upvotes: 3