-- Start
Java. util. concurrent. the atomic package provides the following atomic classes, which are thread-safe classes, but they are not implemented through synchronization and lock, the operation of atomic variables changes to the hardware primitive provided by the platform for concurrent access.
- Atomicboolean -- Atomic Boolean
- Atomicinteger -- Atomic integer
- Atomicintegerarray -- Atomic integer Array
- Atomiclong -- Atomic long integer
- Atomiclongarray -- Atomic long integer Array
- Atomicreference -- Atomic reference
- Atomicreferencearray -- Atomic reference array
- Atomicmarkablereference -- Atomic tag reference
- Atomicstampedreference -- Atomic stamp reference
- Atomicintegerfieldupdater -- used to wrap atomic operations on the integer volatile domain
- Atomiclongfieldupdater -- used to wrap atomic operations on the Volatile domain of a long integer.
- Atomicreferencefieldupdater -- used to wrap atomic operations on the Volatile domain of an object
The main reason for introducing these classes is to implement a so-calledNo lock and no waiting Algorithm. For example, compare and Exchange (CAS). The principle is to compare the current value with the expected value. If the value is the same, the variable does not change. the following example uses synchronization and CAS to implement an ID generator.
Synchronous implementation
class IDGenerator {private int id;public IDGenerator() {}public synchronized int nextInt() {return ++id;}}
CAS Implementation Method
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;}}}
---For more information, see:Java
--Shengming: reprinted, please indicate the source
-- Last updated on 2012-07-16
-- Written by shangbo on 2012-07-16
-- End