Interview Questions

Differences between synchronized and volatile keyword in Java?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

11. Differences between synchronized and volatile keyword in Java?

Its very important question from interview perspective.

Volatile can be used as a keyword against the variable, we cannot use volatile against method declaration.

volatile void method1(){} //it’s illegal, compilation error.
volatile int i; //legal


While synchronization can be used in method declaration or we can create synchronization blocks (In both cases thread acquires lock on object’s monitor).
Variables cannot be synchronized.
Synchronized method:
synchronized void method2(){} //legal

Synchronized block:
void method2(){
synchronized (this) {
//code inside synchronized block.
}
}

Synchronized variable (illegal):
synchronized int i; //it’s illegal, compilatiomn error.

Volatile does not acquire any lock on variable or object, but Synchronization acquires lock on method or block in which it is used.

Volatile variables are not cached, but variables used inside synchronized method or block are cached.

When volatile is used will never create deadlock in program, as volatile never obtains any kind of lock . But in case if synchronization is not done properly, we might end up creating dedlock in program.

Synchronization may cost us performance issues, as one thread might be waiting for another thread to release lock on object. But volatile is never expensive in terms of performance.

DETAILED DESCRIPTION : Differences between synchronized and volatile keyword in detail with programs.

(Continued on next question...)

Other Interview Questions