Java atomic operations

Source: Internet
Author: User

-- 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

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.