3

I have a Map<String,Object> to be converted to a ConcurrentMap<String,Object>

    Map<String,Object> testMap = new HashMap<String,Object>();
    testMap.put("test", null); //This null causing issues in conversion
    testMap.put("test2","123");
    testMap.put("test3",234);
    ConcurrentMap<String,Object> concMap = new ConcurrentHashMap<>(testMap);

I get a null pointer exception. If I copy to a new HashMap<String,Object>

    Map<String,Object> testMap = new HashMap<String,Object>();
    testMap.put("test", null);
    testMap.put("test2","123");
    testMap.put("test3",234);
    Map<String,Object> concMap = new HashMap<>(testMap);

I don't get any errors. Is there a safe way to a Map<String,Object> to a ConcurrentMap<String,Object> without the NullPointerException

Prateek Narendra
  • 1,837
  • 5
  • 38
  • 67

3 Answers3

2

It's in the documentation for ConcurrentHashMap:

Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

As for other ConcurrentMaps, the only other implementation ConcurrentSkipListMap, does not allow null either.

daniu
  • 14,137
  • 4
  • 32
  • 53
  • Please do not edit other answers to include your answer in theirs, thanks. – Zabuzard Jan 15 '19 at 07:50
  • @Zabuza Accidentally edited yours, undid it already in case you haven't noticed. There wasn't really a good reason to "include my answer in yours" since your answer was already the same. – daniu Jan 15 '19 at 08:19
2

If you look into the source code of ConcurrentHashMap you will see, it doesn't allow null key or value -

java.util.concurrent.ConcurrentHashMap#putVal

/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
    if (key == null || value == null) throw new NullPointerException();
shakhawat
  • 2,639
  • 1
  • 20
  • 36
0

The issue is not about converting a HashMap into ConcurrentHashMap. It is more about ConcurrentHashMap being null-safe, it does not allow null values. From its documentation:

Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

daniu
  • 14,137
  • 4
  • 32
  • 53
Zabuzard
  • 25,064
  • 8
  • 58
  • 82