Java Multithreading class: Juc Atomic class: 03 Atomiclongarray Atomic Class

Source: Internet
Author: User
Tags cas

Overview

Atomicintegerarray, Atomiclongarray, Atomicreferencearray are similar in principle and usage to the atomic classes of the 3 array types. This chapter describes an atomic class of Atomiclongarray array types. The content includes:
Atomiclongarray Introduction and Function List
Atomiclongarray Source Analysis (based on jdk1.7.0_40)
Atomiclongarray Example

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

Atomiclongarray Introduction and Function List

In the Java Multithreading Series--"Juc Atom class 02 Atomiclong Atom Class" introduced, Atomiclong is the role of the long shape of atomic operations. The function of Atomiclongarray is to perform atomic operations on "long shaped arrays".

List of Atomiclongarray functions

Creates a new atomiclongarray for a given length. Atomiclongarray (int length)//Creates a new atomiclongarray with the same length as the given array and copies all its elements from the given array. Atomiclongarray (long[] array)//atomically adds the given value to the element of index I. Long Addandget (int i, long delta)//If the current value = = expected value, the value is atomically set to the given update value. Boolean compareandset (int i, long expect, long update)//atomically subtract the element of index I by 1. Long decrementandget (int i)//Gets the current value of position I. A long get (int i)//atomically adds the given value to the element of index I. Long Getandadd (int i, long delta)//The element of index i is reduced by 1 by atomic means. Long getanddecrement (int i)//atomically adds 1 to the element of index I. Long getandincrement (int i)//atomically sets the element of position I to the given value and returns the old value. Long Getandset (int i, long newvalue)//atomically adds 1 to the element of index I. Long incrementandget (int i)//finally sets the element of position I to the given value. void Lazyset (int i, long newvalue)//Returns the length of the array. int length ()//sets the element of position I to the given value. void set (int i, long newvalue)//Returns the string representation of the current value of the array. String toString ()//if the current value = = expected value, the value is atomically set to the given update value. Boolean    weakcompareandset (int i, long expect, long update)

Atomiclongarray Source Analysis (based on jdk1.7.0_40)

Atomiclongarray's Complete source code

/*
* ORACLE proprietary/confidential. Use are subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/

/*
*
*
*
*
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/

Package java.util.concurrent.atomic;
Import Sun.misc.Unsafe;
Import java.util.*;

/**
* A {@code long} array in which elements is updated atomically.
* See the {@link Java.util.concurrent.atomic} package specification
* For description of the properties of atomic variables.
* @since 1.5
* @author Doug Lea
*/
public class Atomiclongarray implements Java.io.Serializable {
Private static final long serialversionuid = -2308431214976778248l;

Private static final unsafe unsafe = unsafe.getunsafe ();
private static final int base = Unsafe.arraybaseoffset (Long[].class);
private static final int shift;
Private final long[] array;

static {
int scale = Unsafe.arrayindexscale (Long[].class);
if (Scale & (scale-1))! = 0)
throw new Error ("Data type scale not a power of");
Shift = 31-integer.numberofleadingzeros (scale);
}

Private long Checkedbyteoffset (int i) {
if (I < 0 | | I >= array.length)
throw new Indexoutofboundsexception ("index" + i);

return Byteoffset (i);
}

private static long byteoffset (int i) {
Return ((long) I << shift) + base;
}

/**
* Creates a new atomiclongarray of the given length, with all
* Elements initially zero.
*
* @param length The length of the array
*/
public Atomiclongarray (int length) {
Array = new Long[length];
}

/**
* Creates a new atomiclongarray with the same length as, and
* All elements copied from, the given array.
*
* @param array The array to copy elements from
* @throws nullpointerexception if array is null
*/
Public Atomiclongarray (long[] array) {
Visibility guaranteed by final field guarantees
This.array = Array.clone ();
}

/**
* Returns The length of the array.
*
* @return The length of the array
*/
Public final int Length () {
return array.length;
}

/**
* Gets the current value at position {@code i}.
*
* @param i the index
* @return The current value
*/
Public final long get (int i) {
Return Getraw (Checkedbyteoffset (i));
}

Private long Getraw (long offset) {
return Unsafe.getlongvolatile (array, offset);
}

/**
* Sets the element at position {@code I} to the given value.
*
* @param i the index
* @param newvalue The new value
*/
Public final void Set (int i, long newvalue) {
Unsafe.putlongvolatile (Array, Checkedbyteoffset (i), newvalue);
}

/**
* Eventually sets the element at position {@code I} to the given value.
*
* @param i the index
* @param newvalue The new value
* @since 1.6
*/
Public final void Lazyset (int i, long newvalue) {
Unsafe.putorderedlong (Array, Checkedbyteoffset (i), newvalue);
}


/**
* Atomically sets the element at position {@code I} to the given value
* and returns the old value.
*
* @param i the index
* @param newvalue The new value
* @return the previous value
*/
Public final long Getandset (int i, long newvalue) {
Long offset = Checkedbyteoffset (i);
while (true) {
Long current = Getraw (offset);
if (Compareandsetraw (offset, current, newvalue))
return current;
}
}

/**
* Atomically sets the element at position {@code I} to the given
* Updated value if the current value {@code = =} The expected value.
*
* @param i the index
* @param expect the expected value
* @param update the new value
* @return True if successful. False return indicates that
* The actual value is not equal to the expected value.
*/
Public final Boolean compareandset (int i, long expect, long update) {
Return Compareandsetraw (Checkedbyteoffset (i), expect, update);
}

Private Boolean Compareandsetraw (long offset, long expect, long update) {
return Unsafe.compareandswaplong (array, offset, expect, update);
}

/**
* Atomically sets the element at position {@code I} to the given
* Updated value if the current value {@code = =} The expected value.
*
* <p>may <a href= "package-summary.html#spurious" >fail spuriously</a>
* and does not provide ordering guarantees, so was only rarely an
* Appropriate alternative to {@code Compareandset}.
*
* @param i the index
* @param expect the expected value
* @param update the new value
* @return True if successful.
*/
Public final Boolean weakcompareandset (int i, long expect, long update) {
Return Compareandset (I, expect, update);
}

/**
* atomically increments by one of the element at index {@code i}.
*
* @param i the index
* @return the previous value
*/
Public final long getandincrement (int i) {
Return Getandadd (i, 1);
}

/**
* atomically decrements by one of the element at index {@code i}.
*
* @param i the index
* @return the previous value
*/
Public final long getanddecrement (int i) {
Return Getandadd (I,-1);
}

/**
* Atomically adds the given value to the element at index {@code i}.
*
* @param i the index
* @param delta the value to add
* @return the previous value
*/
Public final long Getandadd (int i, long delta) {
Long offset = Checkedbyteoffset (i);
while (true) {
Long current = Getraw (offset);
if (Compareandsetraw (offset, current, current + Delta))
return current;
}
}

/**
* atomically increments by one of the element at index {@code i}.
*
* @param i the index
* @return The updated value
*/
Public final long Incrementandget (int i) {
Return Addandget (i, 1);
}

/**
* atomically decrements by one of the element at index {@code i}.
*
* @param i the index
* @return The updated value
*/
Public final long Decrementandget (int i) {
Return Addandget (I,-1);
}

/**
* Atomically adds the given value to the element at index {@code i}.
*
* @param i the index
* @param delta the value to add
* @return The updated value
*/
public long addandget (int i, long delta) {
Long offset = Checkedbyteoffset (i);
while (true) {
Long current = Getraw (offset);
Long next = current + Delta;
if (Compareandsetraw (offset, current, next))
return next;
}
}

/**
* Returns The String representation of the current values of array.
* @return The current values of array of the String representation
*/
Public String toString () {
int iMax = array.length-1;
if (IMax = =-1)
Return "[]";

StringBuilder B = new StringBuilder ();
B.append (' [');
for (int i = 0;; i++) {
B.append (Getraw (Byteoffset (i)));
if (i = = IMax)
Return B.append ('] '). toString ();
B.append (', '). Append (');
}
}

}

Atomiclongarray code is very simple, the following is only Incrementandget () as an example, the principle of Atomiclong is described.
Incrementandget () source code is as follows:

Public final long Incrementandget (int i) {    return Addandget (i, 1);}

Description : The Role of Incrementandget () is to atomically add an element of the long array's index I to 1 and return the value after 1.

Addandget () source code is as follows:

public long addandget (int i, long delta) {    //Check if array is out of bounds    long offset = checkedbyteoffset (i);    while (true) {        //Gets the original value of the index offset of the long array,        long current = Getraw (offset);        Modify Long value        long next = current + Delta;        The value of the index offset of the long array is updated by CAs.        if (Compareandsetraw (offset, current, next))            return to Next;}    }

description : Addandget () first checks if the array is out of bounds. If there is no bounds, the value of the array index i is obtained first, and then the value of I is updated with the CAS function.

Getraw () source code is as follows:

Private long Getraw (long offset) {    return Unsafe.getlongvolatile (array, offset);}

Description : Unsafe is an unsafe object returned by Unsafe.getunsafe (). The elements of a long array are atomically manipulated by the CAS function of unsafe. such as Compareandsetraw () is called the CAS function of unsafe, its source code is as follows:

Private Boolean Compareandsetraw (long offset, long expect, long update) {    return Unsafe.compareandswaplong (array, Offset, expect, update);}

Atomiclongarray Example
 1//Longarraytest.java source 2 import Java.util.concurrent.atomic.AtomicLongArray;  3 4 public class Longarraytest {5 6 public static void main (string[] args) {7 8//New Atomiclongarray Object 9 long[] Arrlong = new long[] {ten,, +, 50};10 atomiclongarray ala = new Atomiclongarray (Arrlong); Ala.set (0, +), + (int i=0, len=ala.length (); i<len; i++) System.out.printf (" Get (%d):%s\n ", I, Ala.get (i)), System.out.printf ("%20s:%s\n "," getanddecrement (0) ", ala.getanddecrement (0 ); System.out.printf ("%20s:%s\n", "Decrementandget (1)", Ala.decrementandget (1)), System.out.printf ( "%20s:%s\n", "Getandincrement (2)", Ala.getandincrement (2)), System.out.printf ("%20s:%s\n", "Incrementandget (         3) ", Ala.incrementandget (3)); System.out.printf ("%20s:%s\n "," Addandget ", ala.addandget (0, 100)); 22 System.out.printf ("%20s:%s\n", "Getandadd", Ala.getAndadd (1, +)), System.out.printf ("%20s:%s\n", "Compareandset ()", Ala.compareandset (2, 31, 1000)); 25 System.out.printf ("%20s:%s\n", "Get (2)", Ala.get (2)); 26}27}

Operation result :

Get (0): 100get (1): 20get (2): 30get (3): 40get (4):  getanddecrement (0):  decrementandget (1):  Geta Ndincrement (2):  Incrementandget (3):      Addandget (+): 199 Getandadd (+):     compareandset (): True              Get (2): 1000

Java Multithreading class: Juc Atomic class: 03 Atomiclongarray 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.