gpt4 book ai didi

java - 在多线程应用中使用LinkedHashMap的get()方法安全吗

转载 作者:行者123 更新时间:2023-11-29 04:52:49 24 4
gpt4 key购买 nike

我想编写一个使用 get() 方法访问 LinkedHashMap 的多线程应用程序(应用程序仅使用 get() 方法从 LinkedHashMap 获取数据)。源码如下:

public class Thread1 implements Runnable {
LinkedHashMap<String, ArrayList<GroupMembers>> group;

public Thread1(LinkedHashMap<String, ArrayList<GroupMembers>> _group) {
group = _group
}

public void run() {
while (true) {
Set<String> groupKeyNames = group.keySet();
for (String groupName : groupKeyNames) {

ArrayList<GroupMembers> members = group.get(groupName);
/* Thread 1 processing */
...

}
}
}
}


public class Thread2 implements Runnable {
LinkedHashMap<String, ArrayList<GroupMembers>> group;

public Thread2(LinkedHashMap<String, ArrayList<GroupMembers>> _group) {
group = _group
}

public void run() {
while (true) {
Set<String> groupKeyNames = group.keySet();
for (String groupName : groupKeyNames) {

ArrayList<GroupMembers> members = group.get(groupName);
/* Thread 2 processing */
...

}
}
}
}

public class Sample {

public static void main(String[] args) throws IOException {

/* Init LinkedHashMap */
LinkedHashMap<String, ArrayList<GroupMembers>> group;
group.put("group1", new ArrayList<GroupMembers>());
group.put("group2", new ArrayList<GroupMembers>());
...
Thread1 t1 = new Thread(group);
t1.start();
Thread1 t1 = new Thread(group);
t2.start();
}
}

在上述多线程应用程序中使用 LinkedHashMap.get() 是否安全?

最佳答案

引用Javadoc :

Note that this implementation is not synchronized. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

...

In insertion-ordered linked hash maps, merely changing the value associated with a key that is already contained in the map is not a structural modification. In access-ordered linked hash maps, merely querying the map with get is a structural modification.)

它是按插入顺序还是按访问顺序取决于您实际如何初始化它 - 这不包括在问题中:

  • 如果您使用 new LinkedHashMap(int, float, boolean) 构造 LinkedHashMap ,它可能是按访问顺序排列的(如果您将 true 作为 boolean 参数传递),在这种情况下它不是是线程安全的
  • 如果您使用任何其他构造函数构造它(或将 false 作为 boolean 参数传递),它将是线程安全的 - 前提是您也不继续使用 groups 在其他任何地方引用。

关于java - 在多线程应用中使用LinkedHashMap的get()方法安全吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34795459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com