guidelines for using atomic packages in Java
This paper starts with concurrent network, author: Fang Fei Introduction
Java from the JDK1.5 began to provide a java.util.concurrent.atomic package, to facilitate the programmer in a multi-threaded environment, without locking the atomic operation. The bottom layer of the atom variable uses the atomic instructions provided by the processor, but the different CPU architectures may provide the same atomic instructions, and may require some form of internal locking, so the method cannot absolutely guarantee that the thread will not be blocked.
Atomic Package Introduction
In the atomic package there are 12 classes, four types of atomic updates, the basic types of atomic updates, Atomic update arrays, atomic update references, and atomic update fields. The classes in the atomic package are basically wrapper classes that are implemented using unsafe. Atomic Update base type class
Used to update the base type by atomic means, the atomic package provides the following three classes: Atomicboolean: Atomic Update Boolean type. Atomicinteger: Atomic update integral type. Atomiclong: Atomic update Long integer type.
The common methods used for Atomicinteger are as follows: int addandget (int delta): Adds the input value to the value in the instance (values in the Atomicinteger) in an atomic manner and returns the result Boolean Compareandset (int expect, int update): If you enter a value equal to the expected value, the value is set to the value as entered in atomic form. int getandincrement (): Add the current value by 1 in atomic terms, note: This returns the value of the self increment. void Lazyset (int newvalue): Eventually set to NewValue, and using Lazyset to set the value may cause other threads to read the old values within a short period of time. More information about this method can be referred to a concurrent network translation of an article "Atomiclong.lazyset is how to work." int getandset (int newvalue): A value that is set to NewValue in atomic form, and the old value is returned.
The Atomicinteger example code is as follows:
01 |
Import Java.util.concurrent.atomic.AtomicInteger; |
03 |
public class Atomicintegertest { |
05 |
static Atomicinteger ai = new Atomicinteger (1); |