本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

对数组元素的易失性访问

发布于2023-09-21 20:50     阅读(503)     评论(0)     点赞(25)     收藏(0)


I am having doubts about the volatile keyword in Java when it comes to arrays (after reading a few questions here and specially this document ).

I have a series of threads reading information from an int array named cardArray, and if an entry does not exist in the array I want to create it. What I use for that is a synchronized method like:

    public synchronized void growArray(int id) {
      if(getIndex(id) == -1) {
        cardArray = Arrays.copyOf(cardArray, cardArray.length + 1);
        cardArray[cardArray.length - 1] = id;
      }
    }

getIndex(int id) is a method which returns the position of such unique id in the array or -1 if the array does not exist. cardArray was declared like: protected volatile int[] cardArray = new int[10];

这背后的想法是两个线程可能想让数组同时增长。由于该growArray()方法是同步的,因此他们必须一一进行。一旦第一个线程使数组增长,后续线程就不应该这样做,因为 getIndex(id) 应该指示 id 已经存在。然而,事实是数组被声明为 avolatile而不是它的元素,这让我怀疑这是否是实际的行为。

这是会发生的情况还是以下线程访问growArray()仍然会尝试使数组增长?如果是这样,除了原子数组之外还有其他选择吗?我在想(如果这不能按我想要的方式工作)cardArray = cardArray在编写元素后添加,但我不知道它是否会产生影响。


解决方案


根据您的要求,您可能想要使用 ArrayList 或 HashSet 或 LinkedHashSet。如果您要使用 Java 编写大量代码,那么熟悉 Java 集合库确实会让您受益匪浅。

以下是一些可用选项的说明:

http://docs.oracle.com/javase/tutorial/collections/implementations/index.html

如果您决定使用 ArrayList,您的实现将如下所示:

// This is how you might create your list.
private List<Integer> myList = new ArrayList<Integer>();

public synchronized void growArray(int id) {
  if( ! cardList.contains(id) ){
    cardList.add(id);
  }
}

如果您使用 HashSet(保证唯一性并自动增长),您可以这样做:

// This is how you might create your list.
private Set<Integer> myList = new HashSet<Integer>();

public synchronized void growArray(int id) {
  cardList.add(id);
}

希望这可以帮助!



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/677401/90480e51fcdae4eeae3f/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

25 0
收藏该文
已收藏

评论内容:(最多支持255个字符)