Search code examples
javamultithreadingvolatile

Will volatile fix this Multi-Thread Code?


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

}

Solution

  • 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.