jQuery in Action, 2nd edition*
The moose likes Threads and Synchronization and the fly likes volatile variable & synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "volatile variable & synchronized" Watch "volatile variable & synchronized" New topic
Author

volatile variable & synchronized

Edward Chen
Ranch Hand

Joined: Dec 23, 2003
Posts: 798
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
Sheriff

Joined: Sep 28, 2004
Posts: 18545
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38045
    
  22
Moving topic as not a "beginning" topic.
 
Consider Paul's rocket mass heater.
 
subject: volatile variable & synchronized
 
Similar Threads
Volatile Variable
Volatile - synchronized ?
difference between static and volatile variables
wait() help
Question regarding Singleton pattern