Volatile keyword in Java - Clarification

Viewed 11212

I am really confused about what I read about the applications of volatile keyword in java.

  1. Is the following statement correct? "a write to a volatile field happens before every subsequent read of the same field"

  2. Ideally when should volatile keyword used?

  3. What is the difference between:

    class TestClass
    {  private int x;
    
       synchronized int get(){return x;}
       synchronized void set(int x){this.x = x;}
    
    }
    

and

class TestClass
{  private volatile int x;

   int get(){return x;}
   void set(int x){this.x = x;}

}
6 Answers
Related