Map Security with concurrentHashMap

The following are two approaches that create an instance of concurrentHashMap. I understand that approach 2 is thread safe, but not 1. But I'm talking to a colleague and him, since both create an instance of concurrentHashMap shouldn't approach 1 also a thread safe as well?

Approach 1:

private static final Map<key, value> map = new ConcurrentHashMap<key, value>();

Approach 2:

private static final ConcurrentHashMap<key, value> concurrentHashMap = new ConcurrentHashMap<key, value>();

Would thank for any clarification on this.

+4
source share
4 answers

In both cases ConcurrentHashMap, it is created , so the thread safety is exactly the same.

ConcurrentHashMapimplements the interface Mapthat you call in example 1. But this does not affect the base object that was created.

+6

, .

Map putIfAbsent ConcurrentMap . put get - , , .

+2

. java-:) . , - . - claner - api obj, . . , .

+1

Map null.

private static final Map<key, value> map;

The next line, in which the object is actually created, in both cases is an instance of ConcurrentHashMap , and the variable map points to its address. This is what matters, the actual instance.

map = new ConcurrentHashMap<key, value>();

So there can be no difference between the two!

0
source

All Articles