Rachel
Rachel

Reputation: 103417

Thread safety with map and concurrentHashMap

Below are two approaches, both creating instance of concurrentHashMap, my understanding is that approach 2 is thread safe but not approach 1. But am having conversation with colleague and per him, since both are creating instance of concurrentHashMap should not approach 1 be also thread safe also?

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 appreciate any clarifications on this.

Upvotes: 4

Views: 155

Answers (4)

spudone
spudone

Reputation: 1277

You are creating a ConcurrentHashMap in both cases, so the thread safety is exactly the same.

ConcurrentHashMap implements the Map interface, which is what you're calling through in example 1. But this has no impact on the underlying object that was instantiated.

Upvotes: 6

Beri
Beri

Reputation: 11610

Both solutions are thread safe. You should get more familiar with java interfaces:) Because both are references to same map implementation. First solution hides that fact through an interface, second doesn't. First approach is even claner- its recommend to use api interface instead of class obj, when it comes to collections. This will help to apply changes to your code. I hope my explanation helps a bit.

Upvotes: 1

Alboz
Alboz

Reputation: 1851

The following only creates a pointer for Map object and instantiates it to null.

private static final Map<key, value> map;

The following line it's where the object is really created, in both cases is an instance of ConcurrentHashMap, and the variable map points to it's address. This is what matters, the actual instance.

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

So there cannot be any difference between the two!

Upvotes: 0

phs
phs

Reputation: 11051

Clearly the object has the same runtime type in both cases.

However, when viewed as a Map the putIfAbsent and other ConcurrentMap methods are hidden from clients. Denying them this and forcing them to use the traditional put and get is the concern I expect your colleague is voicing.

Upvotes: 2

Related Questions