Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 Murach's Java Servlets and JSP this week in the Servlets 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: 18505
    
  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: 37907
    
  22
Moving topic as not a "beginning" topic.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: volatile variable & synchronized
 
Similar Threads
Volatile Variable
Volatile - synchronized ?
difference between static and volatile variables
wait() help
Question regarding Singleton pattern