aspose file tools*
The moose likes Threads and Synchronization and the fly likes atomic Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "atomic " Watch "atomic " New topic
Author

atomic

meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305

I'm wondering, if i could use volatile keyword then what is need of java.util.concurrent.atomic package ?

  • Does volatile give guarantee that it will prevent Memory Consistency Errors ?


  • Suppose

    volatile int i=0;
    i++;

    Does it mean because of volatile i++ is an atomic operation ? if not then what is the use of volatile ?


  • My one regret in life is that I am not someone else.
    - Woody Allen
    Henry Wong
    author
    Sheriff

    Joined: Sep 28, 2004
    Posts: 18896
        
      40

    meeta gaur wrote:
  • Suppose

    volatile int i=0;
    i++;

    Does it mean because of volatile i++ is an atomic operation ? if not then what is the use of volatile ?


  • No. Post increment is *not* an atomic operation.

    As for the use of "volatile"...

  • It disables register caching optimization of the variable.
  • It guarantees that individual set/get operations are atomic for all cases, including for longs and doubles with a 32 bit JVM
  • It disables some "code motion" optimizations on the variable -- to preserve order of changes (and there are memory sync changes as well)


  • Henry

    Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: atomic