Android multithreaded Research (8) Atomic understanding in--java

Source: Internet
Author: User

I. What is atomicity

Atomicity is the smallest unit in the world and indivisible. such as A=0; (a non-long and double type) This operation is indivisible, then we say that this operation is atomic operation. Another example: a++; This operation is actually a=a+1; it is divisible, so he is not an atomic operation.

Second, the atomic operation of the role of non-atomic operation will have a thread safety problem, we need to use synchronization technology (sychronized) to make it an atomic operation. An operation is an atomic operation, then we call it atomic. Some atomic classes are provided under the Java.util.concurrent.atomic package as follows:
Iii. Understanding the Atomicinteger class The following are some common methods in the Atomicinteger class:
Maybe a lot of people and I have the same question, how to achieve atomicity in Atomicinteger? Has the predecessor already to atomiinteger the source code to carry on the analysis "to the Atomicinteger source code Understanding" I here only is quoted, makes a record. Take a look at the source code first:
Public final int getandincrement () {for (;;) {int current = get (), int. next = current + 1;if (Compareandset (current, next)) return to current;}}
Look at this code and the above atomic analysis, from the int next = current + 1 can be seen, it is difficult to ensure the atomicity of the operation, the focus is on the Compareandset (current, Next) method

The function has only two parameters that can be manipulated to really three values, that is, value, expect, update. He used the instruction CAS (compare and swap), which ensured its atomicity by hardware.

The Compareandset function guarantees a comparison, and the assignment of these two steps can be done by an atomic operation.

Then look at the whole function, all the code is put into a loop, if Compareandset () execution fails, then the int current = GET () is indicated; Later, the other thread updates the value, so it loops once, retrieving the current value again until Compareandset () executes successfully.

In conclusion, the Getandincrement () method is not an atomic operation. It just guarantees that he and the other functions are valid for value updates. He exploits optimistic concurrency strategies based on conflict detection. As you can imagine, the probability of failure increases exponentially when the number of optimistic threads is very large.

Iv. Understanding the volatile modifier

In the Java memory model, there are main memories, and each thread has its own memory (for example, a register). For performance, a thread keeps a copy of the variable to be accessed in its own memory. This will cause the same variable to appear in a moment when the value in the memory of one thread may be inconsistent with the value in the memory of another thread, or the value in main memory.
A variable declared as volatile means that the variable is modified by other threads at any time, so it cannot be cache in the thread memory. The following example shows the effect of volatile:

Package Com.codeing.snail.test;public class Testatomic extends Thread {private volatile boolean pleasestop;public void Ru N () {while (!pleasestop) {//Do some stuff ...}} public void Tellmetostop () {pleasestop = true;}}
If Pleasestop is not declared volatile, when the thread executes run, it checks its own copy and cannot know in time that other threads have called tellmetostop () to modify the value of Pleasestop.
Volatile is generally not a substitute for sychronized, because volatile does not guarantee the atomicity of the operation, even if only i++, is actually composed of multiple atomic operations: Read I; Inc; Write I, if multiple threads execute i++,volatile at the same time can only guarantee that I is the same piece of memory, but it is still possible to write dirty data.

The volatile keyword is used to declare simple type variables such as int, float, and Boolean data types. If these simple data types are declared volatile, the operation on them becomes atomic level. But there is a certain limit to this. For example, n in the following example is not an atomic level:

Package Com.codeing.snail.test;public class Testatomic extends Thread {public static volatile int n = 0;public void Run () {for (int i = 0; i < i++) try {n = n + 1;sleep (3);//To make the run result more random, delay 3 milliseconds} catch (Exception e) {}}public static void Ma In (string[] args) throws Exception {Thread threads[] = new Thread[100];for (int i = 0; i < threads.length; i++)//Build 100 Thread Threads[i] = new Testatomic (), for (int i = 0; i < threads.length; i++)//Run 100 threads just established Threads[i].start (); for (int i = 0; i < threads.length; i++)//100 threads are executed after the continuation of Threads[i].join (); System.out.println ("n=" + TESTATOMIC.N);}}
If the operation on N is atomic level, the result of the final output should be n=1000, and when the area code is executed, many of the output n are less than 1000, which indicates that n=n+1 is not an atomic level operation. Reason is a simple variable declared as volatile if the current value is related to the previous value of the variable, then the volatile keyword does not work.

V. Lock and atomic usage scenarios

JDK "The design Atom class is used primarily as a variety of blocks for implementing non-blocking data structures and related infrastructure classes," the document says. the compareandset () method is not a regular replacement method for locking. Apply it only when an object's important update is limited to a single variable "in contrast to locks, the volatile variable is a very simple but also very fragile synchronization mechanism, which in some cases provides better performance and scalability than locking." If you strictly follow the use of volatile conditions-that is, the variable is really independent of the other variables and its own previous values-in some cases you can use the volatile substitution synchronized to simplify the code. However, volatile The code used is often more error-prone than code that uses locks.


Android Multithreading Research (8)--java in the Atomic understanding

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.