Volatile Arrays in Java

Source: Internet
Author: User

Volatile Arrays in Java

A slight complication of Java volatile fields, and one sometimes overlooked, was that declaring an array Volat Ile does not give volatile access to its fields!. At least, it doesn ' t when elements of the array is accessed with "normal" Java syntax. In other words:

    • It is unsafe for call arr[x] = y on a array (even if declared volatile) in one thread and then expect ARR[X] to return y from another thread;
    • On the other hand, it 's safe to call arr = new int[] (or whatever) and expect another thread to then re Ad the new array as that referenced by arr: This is the meant by declaring the array reference volatile .

So, what does we do if we want a truly volatile array in Java, where the array's individual fields has the volatile semantics?

Solution 1:useAtomicintegerarrayOrAtomiclongarray

The Atomicintegerarray class implements an int array whose individual fields can is accessed with VO Latile semantics, via the class's get () and set () methods. Calling Arr.set (x, y) from one thread would then guarantee that another thread calling arr.get (x) would re Ad the value y (until another value is read to position x).

Solution 2:re-write the arrayReferenceAfter each field write

This was slightly kludgy and slightly inefficient (since what would being one write now involves II writes) but I believe it is theoretically correct. After setting a element of the array, we re-set the array reference to be itself:

Volatile int[] arr = new int[...]; ... arr[4] = 100;arr = arr;

The marginal benefit of this technique could is:

    • It may allow you to fix some broken code with minimal changes if you have code already (incorrectly) using a volatile< /c1> array and expecting thread-safe element access;
    • It saves us creating the wrapper object around the array (which is what happens with Integerarray and Longarr Ay);
    • It's more, or less, the only option for an array types with no available atomic wrapper (e.g. a float array).

Volatile Arrays in Java

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.