This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

atomic  RSS feed

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
  •  
    Henry Wong
    author
    Sheriff
    Posts: 23283
    125
    C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!