Java Multithreading class: Juc Atomic class: 04 Atomicreference Atomic Class

Source: Internet
Author: User
Tags cas

Overview

This chapter describes the atomic classes of atomicreference reference types. The content includes:
Atomicreference Introduction and Function List
Atomicreference Source Analysis (based on jdk1.7.0_40)
atomicreference Example

Reprint Please specify source: http://www.cnblogs.com/skywang12345/p/3514623.html

atomicreference Introduction and Function List

Atomicreference is a function of atomic manipulation of an "object".

List of atomicreference functions

Creates a new atomicreference with a null initial value. Atomicreference ()//Creates a new atomicreference with the given initial value. Atomicreference (V initialvalue)//If the current value = = expected value, the value is atomically set to the given update value. Boolean Compareandset (v expect, v update)//Gets the current value. V get ()//is set atomically to the given value and returns the old value. V Getandset (v newvalue)//final set to the given value. void Lazyset (V newvalue)//set to the given value. void set (V newvalue)//Returns the string representation of the current value. String toString ()//if the current value = = expected value, the value is atomically set to the given update value. Boolean Weakcompareandset (v expect, v update)

Atomicreference Source Analysis (based on jdk1.7.0_40)

The source code of Atomicreference.java in Jdk1.7.0_40 is as follows:

public class Atomicreference<v> implements java.io.Serializable {private static final long Serialversionuid =-    1848883965231344442L;    Get unsafe object, the function of unsafe is to provide CAS operation private static final unsafe unsafe = unsafe.getunsafe ();    Private static final long valueoffset; static {try {Valueoffset = Unsafe.objectfieldoffset (AtomicReference.class.getDeclaredField ("Valu      E "));    } catch (Exception ex) {throw new Error (ex);}    }//volatile type private volatile V value;    Public atomicreference (V initialvalue) {value = InitialValue;    Public atomicreference () {} Public final V get () {return value;    Public final void Set (V newvalue) {value = newvalue;    Public final void Lazyset (V newvalue) {Unsafe.putorderedobject (this, valueoffset, newvalue);  Public Final Boolean Compareandset (v expect, v update) {return Unsafe.compareandswapobject (this, Valueoffset,    expect, update);Public Final Boolean Weakcompareandset (v expect, v update) {return Unsafe.compareandswapobject (this, valueoff    Set, expect, update);            Public final V Getandset (v newvalue) {while (true) {v x = Get ();        if (Compareandset (x, NewValue)) return x;    }} public String toString () {return string.valueof (get ()); }}

Description :
Atomicreference source code is relatively simple. It is implemented through "volatile" and "unsafe CAS functions" atomic operations.
Value is a volatile type. This ensures that when a thread modifies the value of value, the value values that other threads see are the most recent value values, that is, the volatile value after the modification.
(02) Set value through CAs. This ensures that when a thread pool sets value through a CAS function (such as the Compareandset function), its operation is atomic, that is, the thread will not be interrupted when manipulating value.

Atomicreference Example
Atomicreferencetest.java Source Import Java.util.concurrent.atomic.atomicreference;public class Atomicreferencetest { Public        static void Main (string[] args) {        //creates two person objects whose IDs are 101 and 102, respectively. Person        p1 = new person (101);        person P2 = new person (102);        Creates a new Atomicreference object, initializes its value to P1 object        atomicreference ar = new atomicreference (p1);        Set up AR through CAs. If the value of AR is P1, it is set to P2.        Ar.compareandset (P1, p2);        Person P3 = (person) ar.get ();        System.out.println ("P3 is" +p3);        System.out.println ("p3.equals (p1) =" +p3.equals (p1));}    } Class Person {    volatile long ID;    Public person (long ID) {        this.id = ID;    }    Public String toString () {        return ' ID: ' +id;    }}

Operation result :

P3 is id:102p3.equals (p1) =false








Result Description :
When you create a new Atomicreference object AR, it is initialized to P1.
This is followed by a CAS function to set it. If the value of AR is P1, it is set to P2.
Finally, get the AR corresponding object and print the result. The result of P3.equals (P1) is false, because the person does not overwrite the Equals () method, but instead takes the Equals () method that inherits from Object.java, whereas the Equals () in Object.java is actually called "= = "To compare two objects, that is, compare the addresses of two objects for equality.

Java Multithreading class: Juc Atomic class: 04 Atomicreference Atomic Class

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.