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. POJ.2142 The Balance (拓展欧几里得)

    POJ.2142 The Balance (拓展欧几里得) 题意分析 现有2种质量为a克与b克的砝码,求最少 分别用多少个(同时总质量也最小)砝码,使得能称出c克的物品. 设两种砝码分别有x个与y个, ...

  2. Linux安装cx_Oracle

    安装依赖包 yum -y install gcc python-devel 确认以下变量都已经设置好了 export ORACLE_HOME=/home/oracle/app/oracle/produ ...

  3. 清华大学计算机系大二 java 小学期考试题(摘自知乎)

    public class Main { public void test(Object o) { System.out.println("Object"); } public vo ...

  4. 洛谷P3935 Calculating (莫比乌斯反演)

    P3935 Calculating 题目描述 若xx分解质因数结果为\(x=p_1^{k_1}p_2^{k_2}\cdots p_n^{k_n},令f(x)=(k_1+1)(k_2+1)\cdots ...

  5. mybatis的模糊查询写法

    mybatis做like模糊查询   1.  参数中直接加入%% param.setUsername("%CD%");      param.setPassword("% ...

  6. linux tar指定文件到指定目录

    项目需求:从远处拷贝压缩文件到本地后并解压,解压后的部分文件拷贝并重命名到其他目录 需求拆分:1.拷贝文件 2.解压文件 3.批量重命名 步骤一查看:http://www.cnblogs.com/dd ...

  7. homebrew常见用法

    1. 安装 Homebrew是mac下安装软件的好帮手, 是使用 ruby 写的,采用 github 来存放信息库,很方便吧. Ruby 已经内置,最好装上 Xcode,因为可能需要一些编译包.然后在 ...

  8. redis cluster以及master-slave在windows下环境搭建

    一.redis cluster环境搭建: 1.了解Redis Cluster原理: 详细了解可参考:http://doc.redisfans.com/topic/cluster-tutorial.ht ...

  9. c# 自定义排序Compare

    .net FrameWork 框架博大精深,用着忘着,计划对自己能够想到知识点梳理一下,此篇是对自定义排序的理解: class Program { static void Main(string[] ...

  10. jsp 安装环境与基本语法

    1.什么是web应用程序? web应用程序是一种可以通过web访问的应用程序.web应用程序的最大好处是用户很容易访问应用程序.用户只需要有浏览器即可,不需要安装其它软件. 2.搭建 java web ...