wood burning stoves 2.0*
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
Author

volatile Vs synchronized

Kapil Madhok
Greenhorn

Joined: Dec 15, 2004
Posts: 2
Hi,

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

Thnx,
Kapil
kri shan
Ranch Hand

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

Joined: Sep 28, 2004
Posts: 18874
    
  40

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.

Henry


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

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
Greenhorn

Joined: Mar 07, 2005
Posts: 9
This is a good article about using volatile & synchronised.
 
 
subject: volatile Vs synchronized