Java Atomic Operations

Source: Internet
Author: User
Tags cas volatile

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

Related Article

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.