Java 在并行测试执行中使用Hashmap作为线程安全
我有一个类用于生成随机值,并将这些随机值放入hashmap。但我已经将测试套件配置为能够并行执行。因此,我已经声明constroctor是私有的,它是这个hashmap的线程安全的。这个机制对吗?。如果不正确,我如何实现它Java 在并行测试执行中使用Hashmap作为线程安全,java,multithreading,hashmap,automated-tests,Java,Multithreading,Hashmap,Automated Tests,我有一个类用于生成随机值,并将这些随机值放入hashmap。但我已经将测试套件配置为能够并行执行。因此,我已经声明constroctor是私有的,它是这个hashmap的线程安全的。这个机制对吗?。如果不正确,我如何实现它 public class RandomData{ private static Hashmap map = new Hashmap(); private RandomData(){} public String getRandomVal(){
public class RandomData{
private static Hashmap map = new Hashmap();
private RandomData(){}
public String getRandomVal(){
/* generate random value and put the map, if this generated
value is not existing in the map, it will return or else
a new value is generated again and return. */
}
}
您有一个
HashMap
的单个实例,该实例在RandomData
的所有实例之间共享。如果多个线程同时尝试更新它(通过调用getRandomVal
),您可能会得到未定义的行为,因为HashMap
不是线程安全的。您可以通过使用Map
的线程安全实现来解决这个问题,例如。hashmap
不是线程安全的。生成变量/方法并不能使其成为线程安全的。您应该使用ConcurrentHashMaps或HashTable
来实现线程安全。不,仅将构造函数设置为私有并不能使类成为线程安全的
public static class RandomData {
private static final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
private RandomData() { }
public String getRandomVal() {
/* generate random value and put the map, if this generated
value is not existing in the map, it will return or else
a new value is generated again and return. */
}
}
这些方法是原子的,保证安全 >已经观察了C++和java标签4多年了,这是我第一次看到有人提到java中的未定义行为。想解释一下你的意思吗?据我所知,Java中没有带并发修改的UB—您可能最终会遇到ConcurrentModificationException。您的数据是否会以这样的方式被破坏,即整个程序是不正确的,比如C++中的?@ FureeHix>代码> CONTRONTIFORIGATIONEXPROCTIONEX/CODE >甚至可以在单个线程中发生——例如,如果您在用<代码> Iterator < /代码>迭代它时修改集合。WRT未定义的行为-也许这不是最好的措辞。但是它绝对是不可确定的-如果你在正确的时间点击映射,它可能工作得很好,它可能会导致
map#get
以一个无休止的循环结束,这将导致整个程序(或者至少是执行它的线程)被卡住。你能更具体地说明这个映射的键/值是什么吗。你能举一个随机值生成和存储的例子吗?
ConcurrentHashMap::computeIfAbsent
ConcurrentHashMap::putIfAbsent