File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes volatile Vs synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "volatile Vs synchronized" Watch "volatile Vs synchronized" New topic

volatile Vs synchronized

Kapil Madhok

Joined: Dec 15, 2004
Posts: 2

Can someone please explain me the difference or advantage/disadvantage of using the volatile & synchronized key words?

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1429
if the variable is volatile, then it's not possible to serialize
Henry Wong

Joined: Sep 28, 2004
Posts: 20521

If you just want to do a simple operation like set a flag, (done = true) or check a flag, (if (done != true) { blah } ), there is really little reason to synchronize in order to be thread safe. You can just declare the variable as volatile and avoid synchronization all-together.

Prior to JDK 1.5, this was probably the only useful case. With 1.5 and later, you have atomic variables, which are build using volatile variable. With atomic variables, you can -- in theory -- avoid synchronization all-together.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
[kri shan]: if the variable is volatile, then it's not possible to serialize

I believe you're thinking of transient, not volatile.

"I'm not back." - Bill Harding, Twister
Ben Hur

Joined: Mar 07, 2005
Posts: 9
This is a good article about using volatile & synchronised.
I agree. Here's the link:
subject: volatile Vs synchronized
It's not a secret anymore!