Volatile in Java

Source: Internet
Author: User
Tags volatile

In the current Java memory model, threads can store variables in local memory (such as the machine's registers), rather than read and write directly in memory. This can cause a thread to modify the value of one variable in main memory, while another thread continues to use its copy of the variable value in the register, resulting in inconsistent data.



To solve this problem, just like in this program, the variable is declared volatile (unstable), which indicates that the JVM, this variable is not stable, each use it to the main memory to read. Generally speaking, the flags shared between tasks in a multitasking environment should be modified with a volatile modifier.


A volatile-modified member variable forces the value of the member variable to be reread from shared memory each time it is accessed by the thread. Also, when a member variable changes, forcing the thread to write the change back to the shared memory. So at any moment, two different threads always see the same value for a member variable.

With the difference between volatile and not volatile, run it, you know.

No volatile:

[Java]View PlainCopy  
  1. Package Com.keyword;
  2. Public class Testwithoutvolatile {
  3. private static Boolean bchanged;
  4. public static void Main (string[] args) throws interruptedexception {
  5. New Thread () {
  6. @Override
  7. public Void Run () {
  8. for (;;) {  
  9. if (bchanged = =!bchanged) {
  10. SYSTEM.OUT.PRINTLN ("! =");
  11. System.exit (0);
  12. }
  13. }
  14. }
  15. }.start ();
  16. Thread.Sleep (1);
  17. New Thread () {
  18. @Override
  19. public Void Run () {
  20. for (;;) {  
  21. bchanged =!bchanged;
  22. }
  23. }
  24. }.start ();
  25. }
  26. }


After running, the program goes into a dead loop and keeps running.

With volatile:

[Java]View PlainCopy  
  1. Package Com.keyword;
  2. Public class Testwithvolatile {
  3. private static volatile Boolean bchanged;
  4. public static void Main (string[] args) throws interruptedexception {
  5. New Thread () {
  6. @Override
  7. public Void Run () {
  8. for (;;) {  
  9. if (bchanged = =!bchanged) {
  10. SYSTEM.OUT.PRINTLN ("! =");
  11. System.exit (0);
  12. }
  13. }
  14. }
  15. }.start ();
  16. Thread.Sleep (1);
  17. New Thread () {
  18. @Override
  19. public Void Run () {
  20. for (;;) {  
  21. bchanged =!bchanged;
  22. }
  23. }
  24. }.start ();
  25. }
  26. }


Program Output! =, and then exit immediately.

However, in many cases, with no volatile, no sense of difference, when to use volatile it? Look at the classes in the JDK that use volatile.

For example, variables in Java.util.regex.Pattern:

[Java]View PlainCopy 
    1. Private Transient volatile Boolean compiled = false;


Also, the variables of Java.lang.System:

[Java]View PlainCopy 
    1. Private static volatile Console cons = null;


In general, when initializing, you need to use volatile.

Variables in the Java.util.Scanner, such as:

[Java]View PlainCopy  
    1. Private static volatile Pattern Boolpattern;
    2. Private static volatile Pattern Separatorpattern;
    3. Private static volatile Pattern LinePattern;


Initialize the Boolpattern code:

[Java]View PlainCopy 
  1. Private static Pattern Boolpattern () {
  2. Pattern bp = Boolpattern;
  3. if (bp = = null)
  4. Boolpattern = BP = Pattern.compile (Boolean_pattern,
  5. pattern.case_insensitive);
  6. return BP;
  7. }

Above, you can use synchronized to lock the Boolpattern, but the synchronized overhead is greater than volatile, and volatile is capable of doing the work above.

Volatile does not guarantee atomic manipulation, so it is easy to read dirty data.

Usage Recommendation: Use volatile on member variables accessed by two or more threads. When the variable to be accessed is already in the synchronized code block, or is a constant, you do not have to use the

Volatile in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.