blitzkriegz
blitzkriegz

Reputation: 9576

Java: ConcurrentHashMap

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"

Upvotes: 2

Views: 3494

Answers (2)

JH.
JH.

Reputation: 4219

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".

Upvotes: 2

Matthew Flaschen
Matthew Flaschen

Reputation: 285057

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.

Upvotes: 10

Related Questions