Introduction and use of volatile keywords

Source: Internet
Author: User
Tags visibility volatile

The primary role of keyword volatile is to make a variable visible in a thread

1. Suppose volatile doesn't exist the problems we will face

public class Printstring implements Runnable
{

    private Boolean iscontinueprint = true;

    public Boolean iscontinueprint () {return
        iscontinueprint;
    }

    public void Setcontinueprint (Boolean iscontinueprint) {
        this.iscontinueprint = iscontinueprint;
    }

    public void Printstringmethod ()
    {
        try
        {
            iscontinueprint)
                { System.out.println ("Run printstringmethod threadname =" + Thread.CurrentThread (). GetName ());
                Thread.Sleep (1000);
            }
        catch (Interruptedexception exception)
        {
            exception.printstacktrace ();
        }
    }

    @Override public
    Void Run () {
        printstringmethod ();
    }
}
public class Test {

    /**
     * @param args
     *
    /public static void main (string[] args)
    {
        try
        {
            printstring mprintstring = new printstring ();
            Thread mthread = new Thread (mprintstring);
            Mthread.start ();
            Thread.Sleep (1000);
            Mprintstring.setcontinueprint (false);//in-server mode, this action modifies the value in the public stack, and the thread's private stack does not modify
        }
        catch ( Interruptedexception e)
        {
            e.printstacktrace ();
        }
    }
}

When the JVM does not stop printstring method in-server mode, there is a notion of a public stack and a thread private stack in-server mode. We modify the value in the public stack by calling Setconinueprinter (false) and do not affect the thread's private stack.

At this point we need to introduce the volatile keyword, which is to force the thread to access the Iscontinueprint value in the public stack.

Using the volatile keyword increases the visibility of instance variables across multiple threads, but the volatile keyword has a fatal flaw that does not support atomicity

The comparison between synchronized and volatile keywords volatile is a lightweight implementation of thread synchronization, so volatile keyword performance is better than synchronized. Volatile can only modify variables, synchronized may modify methods, code blocks volatile not block threads, synchronized block threads volatile ensure data visibility, not guarantee atomicity, Synchronized can guarantee atomicity and can indirectly guarantee visibility, which synchronizes data from public and private memory. volatile resolves the visibility of variables across multiple threads, synchronized solves the synchronization of access resources between multiple threads

Keep in mind that the Java synchronization mechanism revolves around two points: atomicity , visibility between threads . Only if the two points are met can the call be synchronized. The synchronized and volatile two keywords in Java perform the visibility between atomicity and threads, respectively.

volatile is not atomic .
Look at an example

Package Com.sophia.demo;

public class Mythread extends Thread
{
    volatile public static int COUNT;

    private static void Addcount ()
    {for
        (int i = 0; i < i++) 
        {
            count++;
        }
        System.out.println ("Count =" + count);
    }

    @Override public
    Void Run ()
    {
        addcount ();
    }
}
Package Com.sophia.demo;

public class Stringtest {public

    static void Main (string[] args)
    {
        mythread[] mythreads = new mythread[100];< c4/>for (int i = 0; i < mythreads.length i++)
        {
            Mythreads[i] = new Mythread ();
        }

        for (Mythread mythread:mythreads)
        {
            if (null!= mythread)
            {
                mythread.start ();
    }}}
}

The results of the output are not as incremental as we think.

Count =
Count = Count
= 200

Looking closely at the output, we see a result of this, when we add the synchronized method to the Addcount () method to achieve the effect of synchronization. There is no need to use the volatile keyword at this point.
First we analyze a common expression i++ that i = i + 1; This operation is not atomic or not thread safe, the decomposition steps are as follows from the memory of the value of I to calculate I of the value of I to write in memory

Assuming that in the 2nd step, there are other threads modifying the value of I, this time will appear dirty data, the solution is to use the Synchronized keyword. So volatile doesn't deal with the atomicity of the data.
Explain in detail why the thread is unsafe for volatile: Read and load procedures: Copy variables from main memory to the current thread's working memory use and assign procedures: Execute code, change the value of a variable store and write procedures: Store changed variables and write to main memory.

In multithreading, use and assign are multiple occurrences, but the operation is not atomic, that is, after read and load, if the main memory count variable is sent, the value in the thread's working memory will not change because it has been loaded. That is, the value of private and public memory is not the same. At this point, the value of the other thread in the public memory will cause a deviation. Causes the thread to be unsafe. So multiple threads accessing the same variable plus lock is the safest operation.

Java provides a thread-safe integer class, Atomicinteger, atomic operation is an indivisible whole, no other thread can terminal or check in the atomic operation of variables, can be without locks in the case of thread safety

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.