简体   繁体   English

如何测试我对 ConcurrentHashMap 的使用是线程安全的?

[英]How to test that my usage of a ConcurrentHashMap is threadsafe?

I have written the code below and want to test its concurrency.我写了下面的代码,想测试它的并发性。 Even though I have used ConcurrentHashMap , I am not confident that the code is threadsafe because get and update/replace are used on different lines.即使我使用了ConcurrentHashMap ,我也不确定代码是线程安全的,因为获取和更新/替换在不同的行上使用。 Can anyone suggest how to test this?谁能建议如何测试这个?

ConcurrentHashMap<String, int> somemap = new ConcurrentHashMap<>(); 
boolean some_method() {
    somemap.putifAbsent("somekey",value); 
    final int val = somemap.get("somekey");
    if(val < total_count) {
        val++;
    }
    somemap.replace("somekey", val);
}

Can anyone suggest how to test this?谁能建议如何测试这个?

Testing for thread safety is not reliable.线程安全测试不可靠。 The reason is, The specification for a programming language or library may promise that if your multi-threaded program obeys certain rules, then you can expect it to behave in a certain way, but you will practically never find a promise that if your program breaks the rules then it will fail to meet your expectations.原因是,编程语言或库的规范可能 promise 如果您的多线程程序遵守某些规则,那么您可以期望它以某种方式运行,但您实际上永远找不到 promise 如果您的程序中断规则那么它将无法满足您的期望。

I personally have seen a software update go through weeks of unit testing and integration testing, and then be shipped out into the field, where it ran for half a year before a piece of "thread unsafe" code caused it to fail at a customer site.我个人已经看到一个软件更新 go 经过数周的单元测试和集成测试,然后被运送到现场,运行了半年,直到一段“线程不安全”代码导致它在客户站点失败.

The only way to be sure that your multi-threaded program will work, is to prove that (A) it says what you think it says, and (B) it obeys the rules.确保您的多线程程序能够运行的唯一方法是证明(A) 它说的是您认为它说的,以及 (B) 它遵守规则。

Your example obeys the rules, but I don't think it does what you think it does.您的示例遵守规则,但我认为它没有按照您的想法行事。 It has a race condition.它有一个竞争条件。 Namely, two threads both could call get("somekey") at the same time, and both get the same value.也就是说,两个线程都可以同时调用get("somekey") ,并且都获得相同的值。 Then they both could compute the same new value, and they both could put(...) it back.然后他们都可以计算出相同的新值,并且他们都可以put(...)它放回去。 Two calls to some_method() , but the end result is that the value only goes up by one.两次调用some_method() ,但最终结果是该值只增加了一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM