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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With