need any good example of volatile in synchronization

Asked on October 31, 2013
Hi,
I need any good example of volatile in synchronization which is clearly defining the use
of volatile variable.

Replied on November 01, 2013
- Volatile field will be accessed only by one thread at a time (Java will put locks around it).
- Synchronized block or method will be accessed by only one thread at a time for the whole object.
volatile int b;
synchronized int getA(){
return a;
}
synchronized int getB(){
return b;
}
then two threads can access a and b concurrently, but not getA() and getB(). Only one thread can access a synchronized method across the whole object.

Replied on November 02, 2013
Good Example for volatile but need more explanation on volatile