开发者

Java: ConcurrentHashMap

开发者_C百科What is the correct thread safe collection to map an integer and a string in Java? Is ConcurrentHashMap the right way to go?

private volatile ConcurrentHashMap<int, bool> chm;

What is wrong with the above declaration. Eclipse says "Syntax error on token "int", Dimensions expected after this token"


This maps an Integer to a String. In Java, generics must use reference types (Integer, Boolean, etc.), not primitives (int, boolean, etc.)

private final ConcurrentHashMap<Integer, String> chm;

I doesn't need to be volatile, except in the unlikely event you'll be putting new maps into the field from more than one thread. The map itself will take care of synchronizing mutations.


Make sure that you understand that even when using ConcurrentHashMap you can still get inconsistencies, especially if you have a read/write/read area of your code. Multi-operations on that map still need to be synchronized as one "transcation".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜