Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

volatile variable & synchronized

 
Edward Chen
Ranch Hand
Posts: 798
  • 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: 21115
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 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
Posts: 48921
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving topic as not a "beginning" topic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic