--Start
The following atomic classes are provided in the Java.util.concurrent.atomic package, they are thread-safe classes, but they are not implemented through synchronization and locking, and the operation of atomic variables becomes the hardware primitives provided by the platform for concurrent access.
Atomicboolean--Atomic Boolean Atomicinteger--Atomic integral type Atomicintegerarray--atomic integer array Atomiclong--Atomic Long integer Atomiclongarray--Atomic long Integer array at Omicreference--Atomic reference Atomicreferencearray--Atomic reference array Atomicmarkablereference--atomic marker reference Atomicstampedreference--atomic stamp reference at Omicintegerfieldupdater--an atomic operation Atomiclongfieldupdater used to wrap a volatile domain--to wrap atomic operations on a long volatile field Atomicreferencefieldupdater--Used to wrap atomic operations on an object's volatile domain
The main reason for introducing these classes is to implement a so-called lock-free and no wait algorithm . such as: Compare and Exchange (CAS), it is the principle of comparing the current value and expectations, if the same means that the variable has not changed. The following example uses the synchronous and CAs methods to implement an ID generator.
How to implement synchronization
Class Idgenerator {
private int id;
Public Idgenerator () {
} public
synchronized int nextint () {return
++id;
}
}
how CAS is implemented
Class Idgenerator {
private final Atomicinteger id = new Atomicinteger (0);
Public Idgenerator () {
} public
int nextint () {while
(true) {
int oldid = Id.get ();
int NewID = oldid + 1;
if (Id.compareandset (oldid, NewID)) return
NewID;
}
}
--- more See also: Java Fine Extract
-- statement: Reprint please indicate the source
--Last Updated on 2012-07-16
--written by Shangbo on 2012-07-16
--End