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();
   }
 }


48 comments:

  1. 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
  2. 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
  3. This comment has been removed by the author.

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

    ReplyDelete
  5. 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
  6. the blog is very useful, interesting and informative. thank you for sharing the blog with us. keep on updating.
    Informatica Training in Chennai

    ReplyDelete
  7. 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
  8. Volatile means that the variable changes at runtime and that the compiler should not cache its value for any reason. Web Design Bangalore

    ReplyDelete
  9. hi admin.i am really love it your blog.Because your explanation wise all the topics are too good.I got enough knowledge from your blog.Thanks for sharing more..
    Java Training in Marathahalli
    Python Training in Marathahalli


    ReplyDelete
  10. Hi, I am a big follower of your blog. Really very informative post you shared here. Keep sharing this type of informative blog. Waiting for your next update. If anyone wants to become a Java professional learn Java Training in Chennai. Nowadays Java has tons of job opportunities for all professionals. Data Science Training in Chennai

    ReplyDelete
  11. Hi, am a big follower of your blog. I am really happy to found such a helpful and fascinating post that is written in well manner.Get more Java Training in Marathahalli
    Python Training in Marathahalli

    ReplyDelete
  12. Thanks for your nice information, in your Java Training Tutorial i have seen the information about java atomic package, can you explain about this in detailed manner, i am more encouraged to learn about that topic and help me as well.

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

    ReplyDelete
  14. Very nice post to keep sharing... Thanks for giving very nice information from your post… Java Training in Chennai | RPA Training in Chennai

    ReplyDelete
  15. This information is impressive; I am inspired by your post writing style & how continuously you describe this topic.... Java Training in Chennai | Blue prism Training in Chennai

    ReplyDelete
  16. I have read your blog and I gathered some needful information from your blog. Keep update your blog. Java Training in Chennai | Pega Training in Chennai

    ReplyDelete
  17. I am obliged to you for sharing this piece of information here and updating us with your resourceful guidance. Hope this might benefit many learners. Keep sharing this gainful articles and continue updating us.
    Web Designing Course in chennai
    Java Training in Chennai
    website design training
    Web Designing Institute in Chennai
    Core Java Training in Chennai
    Java Training center in Chennai

    ReplyDelete
  18. In the beginning, I would like to thank you much about this great post. Its very useful and helpful for anyone looking for tips to help him learn and master in Angularjs. I like your writing style and I hope you will keep doing this good working.
    Angularjs Classes in Bangalore
    Angularjs Coaching in Bangalore
    Angularjs Institute in Bangalore
    Android Classes in Bangalore
    Android Development Training in Bangalore
    Android Development Course in Bangalore

    ReplyDelete
  19. Nice Post. Looking for more updates from you. Thanks for sharing.

    businessexceltemplates
    Technology

    ReplyDelete
  20. Incredible post. Keep it up. Thank you such a great amount for sharing your profitable blog.Thanks for sharing. CA Firms
    Stock Audit
    Fixed Assets Audit

    ReplyDelete
  21. These piece of information is useful for all java developers and students too. I would definitely recommend this.
    For any Mobile app development assistance do contact us.

    ReplyDelete
  22. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly,
    Python Training Classes in Noida

    ReplyDelete
  23. Hello, I read your blog occasionally, and I own a similar one, and I was just wondering if you get a lot of spam remarks? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me insane, so any assistance is very much appreciated.
    Data science Course Training in Chennai |Best Data Science Training Institute in Chennai
    AWS Course Training in Chennai |Best AWS Training Institute in Chennai
    Devops Course Training in Chennai |Best Devops Training Institute in Chennai
    Selenium Course Training in Chennai |Best Selenium Training Institute in Chennai

    ReplyDelete
  24. Really informative information. If you want to learn Java from the basic level to advance level, feel free to visit Best Java Training Course.

    ReplyDelete
  25. Much thanks for updating this notable guidance here. Undeniably, this might benefit a majority of apprentices. Keep updating and continue sharing.
    English practice App | English speaking app

    ReplyDelete
  26. This is an amazing blog, thank you so much for sharing such valuable information with us. oracle training in chennai

    ReplyDelete

  27. Nice article and thanks for sharing with us. Its very informative



    Tableau Training in Hyderabad

    ReplyDelete




  28. Nice article and thanks for sharing with us. Its very informative



    AI Training in Hyderabad

    ReplyDelete
  29. informative blog , keep posting and dont forget to checkout our blog full stack course in satara

    ReplyDelete