Volatile arrays in Java

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

  • it is unsafe to call arr[x] = y on an array (even if declared volatile) in one thread and then expect arr[x] to return y from another thread;
  • on the other hand, it is safe to call arr = new int[] (or whatever) and expect another thread to then read the new array as that referenced by arr: this is what is meant by declaring the array reference volatile.

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

Solution 1: use AtomicIntegerArray or AtomicLongArray

The AtomicIntegerArray class implements an int array whose individual fields can be accessed with volatile semantics, via the class's get() and set() methods. Calling arr.set(x, y) from one thread will then guarantee that another thread calling arr.get(x) will read the value y (until another value is read to position x).

Solution 2: re-write the array reference after each field write

This is slightly kludgy and slightly inefficient (since what would be one write now involves two writes) but I believe it is theoretically correct. After setting an 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 be:

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

Volatile arrays in Java的更多相关文章

  1. volatile关键字及Java内存模式

    参考文档:https://www.cnblogs.com/_popc/p/6096517.html volatile关键字虽然从字面上理解起来比较简单,但是要用好不是一件容易的事情.它与Java的内存 ...

  2. java.util.Arrays,java.lang.Math,java.lang.System 类的常用方法汇总

    java.util.Arrays类是数组的工具类,一般数组常用的方法包括 二分查找:public static int  binarySearch(array[],int key),返回key的下标i ...

  3. leetcode第四题:Median of Two Sorted Arrays (java)

    Median of Two Sorted Arrays There are two sorted arrays A and B of size m and n respectively. Find t ...

  4. java数组、java.lang.String、java.util.Arrays、java.lang.Object的toString()方法和equals()方法详解

    public class Test { public static void main(String[] args) { int[] a = {1, 2, 4, 6}; int[] b = a; in ...

  5. LeetCode算法题-Intersection of Two Arrays(Java实现-四种解法)

    这是悦乐书的第207次更新,第219篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第75题(顺位题号是349).给定两个数组,编写一个函数来计算它们的交集.例如: 输入: ...

  6. volatile变量,java内存模型

    volatile变量提供了最轻量级的同步机制,当一个变量加上volatile修饰时,会具有一下两个特性 https://blog.csdn.net/u011277123/article/details ...

  7. coding++:Arrays.asList() - java.lang.UnsupportedOperationException异常处理

    这个异常遇到了才知道坑这么大,坑爹的方法. private String[] otherUserFromArray = new String[]{“3”, “4”, “发放”}; List<St ...

  8. Median of Two Sorted Arrays LeetCode Java

    两排序好的数组,找中位数 描述There are two sorted arrays A and B of size m and n respectively. Find the median of ...

  9. Java Arrays类进行数组排序

    排序算法,基本的高级语言都有一些提供.C语言有qsort()函数,C++有sort()函数,java语言有Arrays类(不是Array).用这些排序时,都可以写自己的排序规则. Java API对A ...

随机推荐

  1. redux connect的浅比较说明

    redux的connect方法是一个高阶组件,对包装的组件会在ShouldComponentUpdate中实现一个默认的浅比较. connect形式如下: connect([mapStateToPro ...

  2. Install JDK In Ubuntu

    安装Linux软件包管理器rpm apt install rpm 查看已安装的软件,如JDK rpm -qa|grep jdk #查询所有 找jdk 卸载已安装的软件 rpm -e nodeps 包名 ...

  3. Linux之SSL安全套接字20160704

    使用SSL前,先有 基本的TCP套接字连接.见demo代码 SSL_library_init();//在使用OpenSSL 之前,必须进行相应的协议初始化工作 OpenSSL_add_all_algo ...

  4. [转载]系统管理:update-alternatives

    http://blog.csdn.net/dbigbear/article/details/4398961 好吧,其实博主也是转载的. update-alternatives --display | ...

  5. 【题解】我也不是B ifrog 1112 二分 倍增

    题目传送门:http://ifrog.cc/acm/problem/1112 神奇的倍增二分,长见识了,在此做个记录,分享给大家. 懒得写题解了,直接转YJQ的:http://ifrog.cc/acm ...

  6. eclipse常见问题解决方案

    1.maven项目,启动报错ClassNotFoundException,原因是tomcat下\WEB-INF\classes目录中,java文件没有编译成class文件.解决方法: 在\WEB-IN ...

  7. WPF 分辨率无关性原理

    WPF在计算窗口尺寸大小时使用的是系统的DPI设置.WPF窗口以及窗口中所有的元素都是使用设备无关单位度量.一个设备无关单位被定义为1/96英寸. [物理单位尺寸]=[设备无关单位尺寸]*[系统DPI ...

  8. js对数组的常用操作

    在js中对数组的操作是经常遇到的,我呢在这就列一下经常用到的方法 删除数组中的元素: 1.delete方法:delete删除的只是数组元素的值,所占的空间是并没有删除的 代码: var arr=[12 ...

  9. 杭电多校第八场-A-Character Encoding

    题目描述 In computer science, a character is a letter, a digit, a punctuation mark or some other similar ...

  10. [USACO06NOV] Corn Fields

    https://www.luogu.org/problem/show?pid=1879 题目描述 Farmer John has purchased a lush new rectangular pa ...