-3

I have executed below piece of code expecting getting count as 20000. I have declared count as volatile, but the output is not proper all the time.

package threading;

public class Demo5 {
    private volatile int count =0;
    public static void main(String[] args){
        Demo5 d = new Demo5();
        d.doWork();
    }

    public void doWork(){
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for(int i=0; i<10000; i++){
                    count++;
                }

            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                for(int i=0; i<10000; i++){
                    count++;
                }

            }
        });
        t1.start();
        t2.start();

        try{
            t1.join();
            t2.join();
        }
        catch (InterruptedException  e) {
            e.printStackTrace();
        }
        System.out.println(count+" is count");
    }
}

Later I tried making count as synchronized by putting it inside a synchronized method, and it was working properly.

public synchronized void increment(){
        count++;
    }

Can someone tell me when we should go for volatile and when for synchronized ?

1 Answers1

2

With synchronized you included the increment and set operations in the same critical section. With volatile the increment and the set were separately protected. That means one thread could increment, then the other, then one could set followed by the other, not necessarily in the same order they incremented. volatile can only coordinate single actions; synchronized can coordinate sequences of actions​.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10