concurrenthashmap java [英] concurrenthashmap java

查看:123
本文介绍了concurrenthashmap java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是错误的。

        static ConcurrentHashMap k; //multiple threads have access to k
         X o = k.get("LL");
         o.a = 6;

如果多个线程同时访问k,并获取k(LL), #)没有k.put(ll,o),没有在'o'或'k'同步发生什么?

If multiple threads access k concurrently, and get k("LL"), then update (o.a = #) without k.put("ll",o), without synchronizing on 'o', or on 'k' what happens?

推荐答案

ConcurrentMap具有保证键/值对的原子插入/移除和替换的条件操作。此外,访问ConcurrentMap会创建一个发生 -

A ConcurrentMap has conditional operations that guarantee atomic insert/removal and replacement of key/value pairs. Additionally, accessing a ConcurrentMap creates a happens-before relationship so you can make certain guarantees about the ordering of your code.

在显示的代码中,

X o = k.get("LL");

访问键LL的当前X值。下一行修改a属性。不知道X的实现,这是Java,所以我们知道这里没有方法调用。 如果(且仅当)a属性被标记为volatile,那么访问LL处的X的后续代码将看到a的值为6.如果它不是volatile,则不存在保证在所有。他们可能会看到6,特别是在一个SMP x86的盒子,没有很多线程做的很多的时间。在生产中,在一个大的NUMA盒子上,他们不太可能。可变性带来各种并发症和困难。

accesses the current X value for the key "LL". The next line modifies the a property. Without knowing the implementation of X, this is Java so we know that there is no method call here. If (and only if) the a property is marked as volatile then some subsequent code accessing the X at "LL" will see the a value as 6. If it isn't volatile then there are no guarantees at all. They will probably see 6, particularly on an SMP x86 box, with not many threads doing much at the time. In production, on a big NUMA box, they are less likely to. Mutability brings with it all sorts of complications and difficulty.

一般来说,如果你使用不可变的键,你会发现更容易理解地图的状态值。

Generally, you'll find it is easier to reason about the state the map is in if you use immutable keys AND values.

这篇关于concurrenthashmap java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆