Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 610
Rachel Avatar asked Jan 09 '23 16:01

Rachel


2 Answers

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.

like image 69
spudone Avatar answered Jan 18 '23 04:01

spudone


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.

like image 37
phs Avatar answered Jan 18 '23 04:01

phs