Thread Basics Series (v) Understanding volatile

Source: Internet
Author: User
Tags mutex visibility volatile

Thread Basics Series (iv) Synchronization of threads 2: notify-wait communication mechanism for threads, and condition condition variables

Thread Basics Series (iii) synchronization of Threads: synchronization control, locks and synchronized

Thread Basics Series (ii) thread management: Thread state, control, hibernation, Interrupt,yield, etc.

Thread Basics Series (a) thread creation and startup: Thread creation and startup, join (), daemon thread, callable task.

The key words discussed in this article are volatile.

    1. Volatile usage scenarios

    2. Volatile introduction

    3. Volatile vs synchronized vs lock

1 volatile usage scenarios

official definition of volatile

java Language specification is as follows: The Java programming language allows threads to access shared variables, and in order to ensure that shared variables can be updated accurately and consistently, the thread should ensure that the variable is obtained separately through an exclusive lock. The Java language provides volatile, which in some cases is more convenient than a lock. If a field is declared as a Volatile,java thread, the memory model ensures that all threads see that the value of this variable is consistent.

package com.threadexample.sysn;public class violatiletest extends thread {     boolean keeprunning = true;    public void run ( )  {        while  (keeprunning)  {             //cannot be printed here, otherwise it will affect the demo            //system.out.println ("runing--");         }         system.out.println ("thread terminated.");     }    public static void main (String[] args)  throws interruptedexception {        violatiletest  t = new violatiletest ();         t.start ();         tHread.sleep (;        t.keeprunning = false;  )       system.out.println ("Keeprunning set to false.");     }}

For this example, the desired effect is very simple, the main thread sleeps for 1 seconds and closes the T thread. A running result demonstrates that the thread T does not exit as expected.

If you use the volatile keyword to decorate the keeprunning keyword, you can achieve the desired effect. Why is it?

2.volatile Introduction

The Chinese meaning of volatile is "unstable, capricious". However, in the Java realm, it is translated into "visibility".

In Java, when volatile is used in a scope, Java is guaranteed as follows:

2.1 Guarantee of Order

Java memory model that supports reordering of instructions. Why reordering is mainly considered from the performance optimization level. The main reordering includes the following:

Compiler optimized reordering
Instruction-level parallel reordering
Memory system reordering

Reorder results: The execution result is not changed; from a multithreaded perspective, the order of execution of other threads is unordered, and the order of execution in this thread is sequential from a single-threaded point of view. volatile restricts reordering. Volatile reads and writes establish a happens-before relationship, similar to the application and release of a mutex, and the difference between a mutex is that atomic access cannot be guaranteed like a lock.

2.2 Guaranteed Visibility

According to JMM, each worker thread holds a local cache, respectively. Information communication between threads requires that the thread's local cache is synchronized with the shared cache.

Volatile declared variables do not need to be saved to the local cache, meaning that each thread accesses a volatile scope and reads its current value before continuing, rather than (possibly) using a cached value.

3.volatile vs Synchronized vs Lock

Volatile and synchronized keywords are somewhat similar in function, but there are many differences. I personally prefer to learn by contrast, and it is easy to deepen understanding.

As shown in the example above, it is also possible not to use the volatile keyword, which can be used with synchronous synchronized.

3.1 Use synchronized to implement timed off thread effects.

package com.threadexample.sysn;public class violatiletest extends thread {     private boolean keepRunning = true;    public  Void run ()  {        while  (keeprunning)  {             system.out.println ("runing--");         }        system.out.println (" thread terminated. ");     }    public synchronized void setrunning (Boolean  keeprunning) {        this.keeprunning=keeprunning;     }    public static void main (String[] args)  throws  interruptedexception {        violatiletest t =& NBsP;new violatiletest ();         t.start ();         thread.sleep (+);         t.setrunning (false) ;//        t.keeprunning = false;         system.out.println ("Keeprunning set to false.");     }}


Aspects
Volatile Synchronized or lock
Thread Safety Assurance
Just guarantee visibility
Visibility + atomicity
Relative concurrency
High

Exclusive lock, relatively low

Usage Scenarios

1. Write operations on variables, not dependent on the current value of the variable

2. The variable is not included in the invariant condition with other state variables

3. No lock required when accessing variables


When accessing shared mutable variables

Consider using concurrent containers as much as possible


1. Using Violatile to ensure a thread-safe example, this is a bad way.

Package com.threadexample.sysn;import java.util.concurrent.timeunit;public class counttask  implements Runnable {    private volatile  int count;     public void run ()  {        for ( int i=0;i<100;i++) {            count++;             try {                 timeunit.milliseconds.sleep (Ten);             } catch  (interruptedexception  e)  {                 e.printstacktrace ();            }       &nbSp; }    }    public int getcount () {return   This.count;}     public static void main (String[] args)  throws  Interruptedexception {        counttask ct = new  counttask ();         thread t1 = new thread ( CT),         thread t2 = new thread (CT);         t1.start ();         t2.start ( );         t1.join ();         T2.join ();         system.out.println (Ct.getcount ());     }}

This approach is not thread-safe because there is a state dependency. An increment operation that relies on the previous value.



This article is from a "simple" blog, so be sure to keep this source http://dba10g.blog.51cto.com/764602/1795257

Thread Basics Series (v) Understanding volatile

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.