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();
}
}