发布于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黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!