What is Volatile means in Java

Volatile guarantees this in Java:
1) There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value. (However, there is no guarantee about the relative ordering of volatile reads and writes with regular reads and writes, meaning that it's generally not a useful threading construct.)
2)  After java 5, Volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.
Using volatile may be faster than a lock, but it will not work in some situations.The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.

Where to use Volatile :
Best case will be where where the variable updates should be visible to all threads because The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory". and Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

Danger of Volatile:
Atomic operations are not thread safe with volatile variables. see this Code :

volatile int i;
.
..
i += 5;

Here i += 5 is not thread safe and  this is equivalent to
int temp;
synchronized (i) {
  temp = i;
}
temp += 5;

synchronized (i) {
  i = temp;
}

Solution of this in Java 5: Java Atomic package

Java Atomic package works on principle of CAS (compare and swap). The signature of any CAS method is -

   boolean compareAndSet(expectedValue, updateValue);

As Described in Java Doc:

"This method (which varies in argument types across different classes) atomically sets a variable to the updateValue if it currently holds the expectedValue, reporting true on success. The classes in this package also contain methods to get and unconditionally set values, as well as a weaker conditional atomic update operation weakCompareAndSet described below.
The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors. However on some platforms, support may entail some form of internal locking. Thus the methods are not strictly guaranteed to be non-blocking -- a thread may block transiently before performing the operation."

Instances of classes AtomicBooleanAtomicIntegerAtomicLong, and AtomicReference each provide access and updates to a single variable of the corresponding type. Each class also provides appropriate utility methods for that type.

Example of Increment method in Atomic class :

class Sequencer {
   private final AtomicLong sequenceNumber
     = new AtomicLong(0);
   public long next() {
     return sequenceNumber.getAndIncrement();
   }
 }


19 comments:

  1. Thanks for your ideas. You can also find the details on Affity Solutions, at the Java Developers. The main object of the Affity Solutions is to provide quality web services and is among the few software development company in Nagpur.

    ReplyDelete
  2. Thanks for Information Java is an object-oriented programming language with a built-in application programming interface (API) that can handle graphics and user interfaces and that can be used to create applications or applets. There are many websites and lots of applications that will not work unless you have Java installed, and more are created every day. Java is the fast, secure and more reliable. Java applications are used everywhere from laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet etc. JAVA Online Training

    ReplyDelete
  3. Thanks a lot for these valuable information ! I share some java codes on my blog if you want to check it out: http://berksoysal.tk

    ReplyDelete
  4. great work to you!. Thanks for sharing your advice.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Great post has shared by user .I have gained valuable knowledge form here i appreciate to it . Web Design Companies Bangalore | Website Design Company

    ReplyDelete
  7. I wanted to thank you for this excellent read. I definitely loved every little bit of it.
    soft skills training in chennai

    ReplyDelete
  8. I am really inspired along with your writing abilities as well as with the format to your weblog.
    Is this a paid theme or did you customize it your self? Anyway stay up the nice quality writing, it is rare to peer a nice weblog. like this one today.. seo training in jalandhar

    ReplyDelete
  9. the blog is very useful, interesting and informative. thank you for sharing the blog with us. keep on updating.
    Informatica Training in Chennai

    ReplyDelete
  10. My friend Suggest me this blog and I can say this is the best blog to get the basic knowledge.Thank you so much for this Selenium Training in Chennai

    ReplyDelete
  11. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    iOS Training in Chennai

    ReplyDelete
  12. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.
    Digital Marketing Company in India
    seo Company in India

    ReplyDelete
  13. The blog is absolutely truly incredible. Lots of large information and inspiration, both of which we all need.
    SEO Company in Bangalore, SEO Services in Bangalore

    ReplyDelete
  14. Volatile means that the variable changes at runtime and that the compiler should not cache its value for any reason. Web Design Bangalore

    ReplyDelete
  15. I absolutely admired every bit of it and i additionally accept you book apparent to analysis out fresh things in your site.
    UI UX Design Companies in Bangalore, Web Application Development in Bangalore

    ReplyDelete
  16. I have read your blog its very attractive and impressive. I like it your blog. Java Training in Chennai

    ReplyDelete
  17. You made some good points there. I did a search on the topic and found most people will agree with your blog.
    Java Training in Chennai

    ReplyDelete
  18. I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in IBM Endpoint Manager 9.2 Platform Fundamentals, kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor led training on IBM Endpoint Manager 9.2 Platform Fundamentals. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
    For Demo Contact us.
    Nitesh Kumar
    MaxMunus
    E-mail: nitesh@maxmunus.com
    Skype id: nitesh_maxmunus
    Ph:(+91) 8553912023
    http://www.maxmunus.com/

    ReplyDelete

  19. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

    Android App Development Company

    ReplyDelete