Java-multi-thread in-depth analysis (4) Volatile analysis, java-volatile

Source: Internet
Author: User

Java-multi-thread in-depth analysis (4) Volatile analysis, java-volatile

(1) Use of volatile

1. Use Cases

(1) status ID. Used to indicate the occurrence of an important event in real time, such as initialization or shutdown.

Volatile boolean toShutdown;... public void shutdown () {toShutdown = true;} public void doWork () {while (! ToShutdown) {// execute the operation }}
(2) secure object Publishing. Volatile is one of the methods for handling secure object Publishing. For more information, see here.
class Singleton{        private volatile static Singleton instance = null;                 private Singleton() {                     }                 public static Singleton getInstance() {            if(instance==null) {                synchronized (Singleton.class) {                    if(instance==null)                        instance = new Singleton();                }            }            return instance;        }    }

In the classic dual-check Singleton mode, the volatile variable does not cause the object to fail to be initialized when the new object is created.

2. Generally, volatile must meet the following two conditions:
(1) write operations on variables do not depend on the current value
(2) The variable is not included in the variant with other variables.

For 1, because the volatile variable does not guarantee atomicity, one thread executes I ++ and the other thread obtains the value of I, but may not necessarily obtain the latest value.

For 2,

    volatile int min = 0;    volatile int max = 10;    public boolean setA(int newMin) {        if (newMin > max) {            return false;        }        min = newMin;        return true;    }        public boolean setB(int newMax) {        if (newMax < min) {            return false;        }        max = newMax;        return true;    }
When one thread calls setA (8) and one thread calls setB (2), it may get min = 8 and max = 2, which is inconsistent with the original code design intent.


(2) Principle Analysis

Volatile:

Volatile Singleton instance = new Singleton ();

When the instance variable is being written, the lock command is added to the Assembly.

The role of the lock command:

1. Data in the thread working memory will be immediately written back to the main memory during write operations

2. When the data is written back to the primary memory, the cache of the data in other CPUs will become invalid. The next time you read the data, you need to obtain the data from the primary memory again.

/*** Volatile test ** @ author peter_wang * @ create-time 10:11:57 */public class ThreadVolatileDemo {private boolean isStop = false; private void changeStatus () {isStop =! IsStop;}/*** @ param args */public static void main (String [] args) {final ThreadVolatileDemo test = new ThreadVolatileDemo (); Thread thread1 = new Thread () {@ Override public void run () {System. out. println ("try to exit start"); while (true) {// always checks whether the isStop variable updates if (test. isStop) {// A1 System. out. println ("exited successfully"); System. exit (0) ;}}}; thread1.start (); try {Thread. sleep (1, 3000); test. changeStatus ();} catch (InterruptedException e) {e. printStackTrace ();}}}
The A1 part repeatedly reads the isStop value, but reads data from the thread's working memory and hits the data continuously. The data block is not easy to replace, increasing the probability of reading to the old value. Change the isStop variable to volatile. After the variable is modified, it will be immediately written back to the main memory. A1 reads the thread's working memory and reads the latest value from the main memory.



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.