File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

volatile Vs synchronized

 
Kapil Madhok
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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

Thnx,
Kapil
 
kri shan
Ranch Hand
Posts: 1453
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if the variable is volatile, then it's not possible to serialize
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[kri shan]: if the variable is volatile, then it's not possible to serialize

I believe you're thinking of transient, not volatile.
 
Ben Hur
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a good article about using volatile & synchronised.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic