The role of the atomic package:
Allows programmers to perform atomic operations without locks in a multithreaded environment
Atomic Package Core:
The class in the atomic package is basically a wrapper class implemented using unsafe, and the core operation is CAS atomic operation
About CAs
Compare and swap, compare and replace techniques, compare the expected value to the value of the current variable (compare), or replace the current variable with the new value if equal (swap), otherwise do not operate;
Modern CPUs have widely supported CAS directives, and if not, the JVM will use spin locks, which, like mutexes, need to acquire a lock before accessing the shared resource, but the mutex causes the thread to sleep, and the spin lock loops until the lock is acquired;
In addition, it is important to note that the ABA problem in CAS operations, when the expected value compared to the value of the current variable, even if the equality is not guaranteed that the variable has not been modified, because the variable may change from a to B and then back to a, to solve the problem, you can add a version number of the variable, the version number is incremented each Compare the value and version number of the variable at the same time.
Atomic package provides four ways to update atoms
- atomically Update base type
- atomically Update an array
- Atomic Update Reference
- atomically Update Field
atomically Update base type
The following three classes are atomically updating the base type
- Atomicboolean: Atomic Update Boolean type.
- Atomicinteger: Atomic update integral type.
- Atomiclong: Atomic update Long integer.
Take Atomicinteger as an example:
Package Cn.com.example.concurrent.atomic;import java.util.concurrent.atomic.atomicinteger;/** * Created by Jack on 2017/1/7. */public class Atomicintegertest extends Thread { private atomicinteger Atomicinteger; Public Atomicintegertest (Atomicinteger atomicinteger) { This.atomicinteger = Atomicinteger; } @Override public Void Run () { int i = Atomicinteger.incrementandget (); System.out.println ("generated out number :" + i); } public static void Main (string[] args) { Atomicinteger counter = new Atomicinteger (); for (int i = 0; i < i++) {//10 threads New Atomicintegertest (counter). Start ();}} }
Output:
Generated out number:1generated out number:2generated off number:3generated out number:4generated Out number:5generated out number:6generated out number:7generated out number:8generated out number:9generated out number:10
Note: The atomic package provides three basic types of atomic updates, and the remaining Java basic types are char,float and double, which can be updated by referring to the Atomicboolean idea. Atomicboolean is implemented by turning a Boolean into an integer and then calling Compareandswapint for a CAs, similar to short and byte can be turned into shaping, float and Double can be processed using float.floattointbits,double.doubletolongbits for shaping and long shaping
atomically Update an array
The following three classes are atomically updating an array
- Atomicintegerarray: Atoms update elements in an integer array.
- Atomiclongarray: Atoms update elements in an array of long integers.
- Atomicreferencearray: Atoms update elements in an array of reference types
Taking Atomicintegerarray as an example, the method is much like the Atomicinteger, and the index of the array subscript
Package Cn.com.example.concurrent.atomic;import Java.util.concurrent.countdownlatch;import java.util.concurrent.atomic.atomicintegerarray;/** * Created by Jack on 2017/1/7. */public class Atomicintegerarraytest {private static int threadcount = 1000; private static Countdownlatch countdown = new Countdownlatch (threadcount); Static int[] values = new INT[10]; static Atomicintegerarray ai = new Atomicintegerarray (values); private static class Counter implements Runnable {@Override public void run () {for (int i = 0; I < 100; i++) {for (int j = 0; J <; J + +) {//all elements +1 ai.getandincrement (j); }} countdown.countdown (); }} public static void Main (string[] args) throws Interruptedexception {thread[] threads = new Thread[thread Count]; for (int i = 0; i < ThreadCount; i++) {threads[i] = new Thread (new Counter ()); } foR (int i = 0; i < ThreadCount; i++) {Threads[i].start (); } countdown.await (); for (int i = 0; i < i++) {System.out.println (Ai.get (i) + ""); } System.out.println (); for (int i = 0; i < i++) {System.out.println (Values[i] + ""); } }}
Output:
It is important to note that the array value is passed through the construction method, and then Atomicintegerarray copies the current array, so when Atomicintegerarray modifies the inner array elements, the incoming array is not affected.
Atomic Update Reference
The following three classes are atomically updating references, and unlike others, update references can update multiple variables instead of a variable
- Atomicreference: Atomic update reference type.
- Atomicreferencefieldupdater: Atom updates a field in a reference type.
- Atomicmarkablereference: Atom updates A reference type with a tag bit.
Taking Atomicreference as an example
Package Cn.com.example.concurrent.atomic;import java.util.concurrent.atomic.atomicreference;/** * Created by Jack on 2017/1/7. */public class Atomicreferencetest {public static void Main (string[] args) { //creates two person objects whose IDs are 101 and 102, respectively. Person p1 = new person (101); person P2 = new person (102); Creates a new Atomicreference object, initializes its value to P1 object atomicreference ar = new atomicreference (p1); Set up AR through CAs. If the value of AR is P1, it is set to P2. Ar.compareandset (P1, p2); Person P3 = (person) ar.get (); System.out.println ("P3 is" + p3); System.out.println ("p3.equals (p1) =" + P3.equals (p1));} } Class Person { volatile long ID; Public person (long ID) { this.id = ID; } Public String toString () { return ' ID: ' + id; }}
Output:
P3 is id:102p3.equals (p1) =false
When you create a new Atomicreference object AR, it is initialized to P1.
This is followed by a CAS function to set it. If the value of AR is P1, it is set to P2.
Finally, get the AR corresponding object and print the result. The result of P3.equals (P1) is false, because the person does not overwrite the Equals () method, but instead takes the Equals () method that inherits from Object.java, whereas the Equals () in Object.java is actually called "= = "To compare two objects, that is, compare the addresses of two objects for equality.
atomically Update Field
The following three classes are atomically updating fields
- Atomicintegerfieldupdater: An update to an Atomic update integer field.
- Atomiclongfieldupdater: atomically updates the updater of the long field.
- Atomicstampedreference: Atomic updates a reference type with a version number that resolves an ABA problem that may occur when atomic updates are used with CAs.
Taking Atomicintegerfieldupdater as an example
package Cn.com.example.concurrent.atomic;import java.util.concurrent.atomic.atomicintegerfieldupdater;/** * Created by Jack on 2017/1/7. */public class Atomicintegerfieldupdatertest {//Create Atomic Updater and set properties for object classes and objects that need to be updated private static Atomicintegerfieldupdater <User> a = Atomicintegerfieldupdater.newupdater (User.class, "old"); public static void Main (string[] args) throws Interruptedexception {//Set Conan's age is 10 years old user Conan = new user ("C Onan ", 10); Conan grew one year old, but still output old age System.out.println (A.getandincrement (Conan)); Output Conan now Age System.out.println (A.get (Conan)); } public static class User {private String name; public volatile int old; Public User (String name, int old) {this.name = name; This.old = old; } public String GetName () {return name; } public int Getold () {return old; } }}
Output:
1011
Note: Old needs to be declared as volatile
Java.util.concurrent.atomic Package Detailed