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 variable & synchronized

 
Edward Chen
Ranch Hand
Posts: 798
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if I have a volatile variable, do I still need to synchronized it ?

In Doc, it said, volatile will force thread NOT to cache object, only one copy in main memory, but it doesn't say concurrent access is safe.

for example,



Thanks.
 
Henry Wong
author
Marshal
Pie
Posts: 20826
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
Edward Chen wrote:if I have a volatile variable, do I still need to synchronized it ?

In Doc, it said, volatile will force thread NOT to cache object, only one copy in main memory, but it doesn't say concurrent access is safe.


It depends on the operation. A single get or set of the reference is atomic. Anything more than that, is not, and will require you to use the atomic classes (or synchronization).

Henry
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving topic as not a "beginning" topic.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic