Java multi-threaded sentiment two

Source: Internet
Author: User
Tags set time visibility volatile

Write in front

This is the Java multi-threaded sentiment of the second blog, mainly on the Java level of some support for concurrency. The first blog address is:http://zhangfengzhe.blog.51cto.com/8855103/1607712 The next blog will introduce the thread pool and some synchronization tool classes.


Directory

9. Overview of concurrent memory models and concurrency issues

Analysis of volatile and synchronized principles

The principle of threadlocal and its application in struts/spring

Atomic.

. Lock


An overview of concurrent memory models and concurrency problems

First look at a diagram:


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/59/76/wKioL1TUH5Cz58H9AAC-L63M7JY507.jpg "title=" Thread02.png "alt=" Wkiol1tuh5cz58h9aac-l63m7jy507.jpg "/>


In the case of multicore CPUs, each CPU has its own caching cache, and when multiple CPUs operate on the same piece of memory, it is clear that the cache is inconsistent.


Then, let's look at the multithreaded work model:


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/59/7A/wKiom1TUISaB7uG2AAENAumeHqk464.jpg "title=" Thread03.png "alt=" Wkiom1tuisab7ug2aaenaumehqk464.jpg "/>


From the above model diagram, you can get the following conclusions:


First, thread communication within the same process (data exchange) is implemented through memory


Second, each thread, when operating, will first copy a copy of the main memory into its own working memory, and when the calculation is completed, the data in the working memory will be flushed to main memory at some point. Obviously if we do not provide a mechanism to guarantee the order of the Load/save operations of each thread, then it will cause a variety of problems.


It is important to note that:

Communication between Java threads is controlled by the Java Memory Model (Jmm:java), JMM determines when a thread's write to a shared variable is visible to another thread. In addition, in order to achieve optimal performance, Java allows the compiler to rearrange instructions without modifying the program semantics and single-threaded execution results, allowing the CPU to determine the order in which the instructions are executed, although in a multithreaded environment it is possible to cause problems with command rearrangement.


Summarize:

In a multithreaded environment, when we consider concurrency problems, we need to pay attention to the following points:

Atomicity: guarantees that several operations on a thread are either successful together or not, and no other threads are allowed to break.

Visibility: When a thread is working on a shared variable, when it is visible to other threads.

Sorting: Ensure that the order in which the programs are executed is in the order of the Code.



Analysis of volatile and synchronized principles

Volatile and synchronized are 2 keywords that Java provides for concurrency support at the syntactic level.


What is synchronized locked in?


Only understand what locks, can be based on business conditions to construct an object, lock it, to achieve the purpose of synchronization, and to optimize the synchronized lock granularity!


Synchronized (obj) {

...

}


It is important to note that the lock is an object (a normal object or a class) and is not just a synchronized {} area. This means that synchronized (obj) and any other synchronized (obj) are mutually exclusive. It is important to note that the subclass objects, the parent class objects, class classes they are 3 different objects, are 3 different "locks".


What did synchronized do behind the scenes?


First, at the same time, only one thread can get the "key" into the critical area.

Second, when entering a critical region, the working cache of the thread fails, forcing the latest value to be read from main memory

Third, when you exit the critical zone, the working cache of the thread is forced to flush to main memory

Four, when this thread over, another thread to get "key", repeat the above 3 steps


In fact, through the above analysis, synchronized guarantees:

Atomicity: Because only one thread can execute this code at any time

Visibility: Because threads are forced to interact with main memory when they enter or exit a critical region, the current thread can see the changes after the previous thread operation

Order: Because the critical area is actually a single-threaded execution environment, there is no natural problem.



Volatile

For common shared variables, when the interaction between working memory and main memory is not deterministic, it can cause visibility issues. The volatile keyword is specifically designed to ensure visibility in Java threads. In fact, we can assume that the read and write operations of volatile variables between multiple threads are performed directly in the main memory and are invalidated in the working cache. At the same time, JMM also guarantees a certain "order" of volatile variables before and after operation, but does not guarantee atomicity. Therefore, volatile provides a part of the function of the synchronized, the cost is less than a code of synchronization lock mechanism, but in the business scenario, often requires the atomicity of operations, so volatile application scenarios are limited. For example, a typical volatile application scenario is as follows:


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/59/79/wKioL1TUN_rwz1S2AADyZEVYONY383.jpg "title=" Thread04.png "alt=" Wkiol1tun_rwz1s2aadyzevyony383.jpg "/>


Because read threads do not need to be locked to execute concurrently, this reduces the synchronized code area overhead by volatile.



The principle of threadlocal and its application in struts/spring

To thoroughly understand the threadlocal, but also to see its source!


For threadlocal, the most common method we use is: Get ()/set (value)/remove () these 3 operations. So first look at the source code of the Set (value) method:


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/59/7F/wKiom1TUYhXCB1viAAB-6--R7pE656.jpg "title=" Thread05.png "alt=" Wkiom1tuyhxcb1viaab-6--r7pe656.jpg "/>


Description

At set time, the current thread is fetched, and a threadlocalmap is obtained through the current thread, and if so, the user-supplied value is set to Threadlocal as key.


Follow the Getmap (Thread) and Createmap (Thread,t) methods:


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/59/80/wKioL1TVakbS7gUcAAAyeH9XK-I690.jpg "title=" Thread06.png "alt=" Wkiol1tvakbs7gucaaayeh9xk-i690.jpg "/>


Returns the member variable threadlocals of a thread, looking at the source code discovery for the following thread:

Threadlocal.threadlocalmap threadlocals = null;


Threadlocalmap is the inner class defined in the Threadlocal class, but it is a member variable of thread!


In fact, we can come to the conclusion that:


To store something in a threadlocal variable is equivalent to keeping something in a map member variable of the current thread, key is the Threadlocal object, and value is what you want to put. In this case, it can be taken anywhere on a thread and is absolutely safe because it is a property of the thread itself and not shared by multiple threads.


You can look at Createmap (thread,t) To verify the above conclusions:

void Createmap (Thread T, T firstvalue) {t.threadlocals = new Threadlocalmap (this, firstvalue); }


It is due to the characteristics of threadlocal, which makes it application in struts/spring!


When a request arrives at the Web container, in general, the Web container pulls out an idle thread from the thread pool, and how does the requested data, such as request, relate to this thread? STRUTS2 will encapsulate the requested data and put it into threadlocal, so the request data in one thread is absolutely safe!


And in spring, threadlocal is everywhere!


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/59/84/wKiom1TVcCPDX4CIAAC-IbgxKgU436.jpg "title=" Thread08.png "alt=" Wkiom1tvccpdx4ciaac-ibgxkgu436.jpg "/>

In the DAO layer, we did not pass the connection to the DAO method explicitly, how did it get to connection?

Why do we get the same connection in one thread of spring?

......




Atomic

atomic, in English means "atomic", The JDK provides us with a set of atomic operations classes in the Java.util.concurrent.atomic package, which can be understood directly by looking at an example.

Package test14;import java.util.concurrent.atomic.atomicinteger;public class integertest  {public static void main (String[] args)  throws interruptedexception { Addtask task = new addtask (1); Thread[] threads = new thread[10];for (int i = 0 ; i <  10 ; i++) {threads[i] = new thread (Task); Threads[i].start ();} for (thread t : threads) {t.join ();} System.out.println ("The end result is:"); Task.display ();}} class addtask implements runnable{private int i = 0;//private  atomicinteger atomic ;p Ublic addtask (int i) {this.i = i;//this.atomic =  new atomicinteger (i);} @Overridepublic  void run ()  {try {thread.sleep (1000);}  catch  (interruptedexception e)  {e.printstacktrace ();} I = i + 1;//atomic.incrementandgeT ();} Void display () {System.out.println ("i = "  + i);//system.out.println ("Atomicinteger  =  " + atomic);}}


When the variable is a normal int type, because i = i + 1 This operation is not atomic, resulting in concurrency problems, often results <= 11, if you use Atomicinteger, will always get 11.


Under the Java.util.concurrent.atomic package, an atomic operation class of type Integer/long/boolean is provided, as well as an atomic operation class for an array/reference type. Below, taking Atomicinteger as an example, the implementation principle of atomic operation class is simply analyzed.


Note the member variables in the Atomicinteger class:

private volatile int value;


Note that with the volatile modifier, when concurrency occurs, other threads are visible!


Let's analyze a method and take Incrementandget () as an example:


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/59/84/wKiom1TVfoWzVeNjAAB1Q_ck9wg022.jpg "title=" Thread09.png "alt=" Wkiom1tvfowzvenjaab1q_ck9wg022.jpg "/>


Note that get () returns the member variable value, which is actually compared and modified with Compareandset, if current is compared with the value of the present value, if it is consistent, the old values are identical, and no other thread has modified, then the old value can be set to next, Otherwise die loop, try to modify! In fact, this is called the CAS mechanism.



Lock

We can not only achieve the purpose of locking through the Synchronized keyword, but also through the java.util.concurrent.locks.Lock to achieve the goal.


For example, we often write:

Lock.lock (); try{//xxx Business Operation}finally{//Be sure to release the lock Lock.unlock ();}




This article is from the "I want to surpass myself" blog, please be sure to keep this source http://zhangfengzhe.blog.51cto.com/8855103/1612581

Java multi-threaded sentiment two

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.