Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A team replaced HashMap with ConcurrentHashMap and Map.copyOf in several places for thread safety. After deployment, some requests fail with NullPointerException deep inside map code, and a cache that used computeIfAbsent seems to never store some keys. Explain the likely causes.

Both problems come from null. ConcurrentHashMap, Map.copyOf and Map.of reject null keys and values, and even get(null) throws on them, so code paths that used to store or look up nulls in a HashMap now throw NullPointerException from inside the map. merge(key, null, f) throws in every Map implementation. And computeIfAbsent never stores a mapping when the function returns null, so lookups whose answer is no result are recomputed on every call. We fix it by modelling absence explicitly, with Optional values or a sentinel, by auditing callers that relied on nulls, and by testing the null paths before such a migration.

Why this question is asked

Swapping HashMap for ConcurrentHashMap looks like the safest change imaginable: same interface, more safety. That is why its failures surprise teams. The two map types make different promises about null, and Map.copyOf adds its own, stricter ones. Interviewers ask this because it tests whether we read contracts rather than interfaces, and whether we can explain a cache that silently does not cache. In this answer, we will recap which maps accept null, reproduce the NullPointerExceptions, explain merge(), look at why computeIfAbsent seems to forget some keys, and then fix both problems and plan the tests that should have come first.

1A Quick Recap: Same Interface, Different Rules About null

All these classes implement java.util.Map, but the interface lets each implementation decide whether it accepts null keys and values. HashMap accepts one null key and any number of null values. ConcurrentHashMap rejects both, because in a concurrent map a null from get() must mean absent without a second call. The immutable maps from Map.of and Map.copyOf reject both as well, and they also reject null in queries: get(null) and containsKey(null) throw.

So a change from new HashMap<>() to new ConcurrentHashMap<>() or Map.copyOf(map) compiles without a single warning, and every place where a null key or value can appear becomes a runtime failure.

2Reproducing the NullPointerExceptions

Here are the patterns that typically worked before the migration and fail after it.

Java
Map<String, String> before = new HashMap<>();
before.put("discount", null); // fine
before.get(null); // null, fine
Map<String, String> chm = new ConcurrentHashMap<>();
chm.put("discount", null); // NullPointerException at ConcurrentHashMap.putVal
chm.get(null); // NullPointerException
Map<String, String> source = new HashMap<>();
source.put("discount", null);
Map<String, String> frozen = Map.copyOf(source); // NullPointerException: null value
Map.of("a", "1").containsKey(null); // NullPointerException even for a query

Notice where the stack traces point: into ConcurrentHashMap.putVal or ImmutableCollections, deep inside map code. The real cause is upstream, wherever the null came from, for example an optional request field, a column that is sometimes NULL or a lookup that found nothing. That is why these failures appear only for some requests: the ones whose data contains a null.

3Why merge() Throws Even in a HashMap

merge(key, value, remapping) puts value if the key is absent, and otherwise replaces the current value with remapping(old, value). Its contract uses null from the remapping function to mean remove the entry, so a null value argument would be meaningless. Every implementation, including HashMap, therefore throws NullPointerException when the value passed to merge is null.

Java
Map<String, Integer> counts = new HashMap<>();
Integer delta = parseOrNull(request.param("qty")); // null when the parameter is missing
counts.merge("apples", delta, Integer::sum); // NullPointerException in any Map

If the code moved from a get-then-put pattern to merge() during the same migration, which is common because merge is atomic on ConcurrentHashMap, the null that used to be stored quietly now throws.

4Why computeIfAbsent Never Stores Some Keys

computeIfAbsent(key, f) returns the existing value if there is one; otherwise it calls f(key) and stores the result. Its contract adds one rule: if f returns null, no mapping is recorded, and the method returns null. That is true for HashMap and ConcurrentHashMap alike. The rule exists because a null value cannot be stored in a ConcurrentHashMap, and the Map interface keeps the behaviour consistent everywhere.

Java
Map<String, Product> cache = new ConcurrentHashMap<>();
Product p = cache.computeIfAbsent("SKU-404", repo::findOrNull); // database query, returns null
Product q = cache.computeIfAbsent("SKU-404", repo::findOrNull); // database query again
System.out.println(cache.containsKey("SKU-404")); // false: nothing was stored
Step throughWhat computeIfAbsent does
  1. Key present?
    YesReturn the existing valueNoCall the mapping function
  2. Function returned null?
    YesStore nothing, return nullNoStore the value, return it
  3. Next call for a missing productfunction runs again: another database query

3 steps in order. Play them, or step through them one at a time.

So every lookup for a product that does not exist goes to the database, every time. If those lookups are frequent, for example bots probing random SKUs, the cache provides no protection exactly where it is most needed, and the database sees the full load. That is the cache that seems to never store some keys.

5Fixing It: Model Absence Explicitly

The common fix for both problems is to stop using null to mean something. For the cache, we store the fact that the product does not exist, either as an Optional or as a sentinel object.

Java
Map<String, Optional<Product>> cache = new ConcurrentHashMap<>();
Optional<Product> p = cache.computeIfAbsent("SKU-404", sku -> Optional.ofNullable(repo.findOrNull(sku)));
Optional<Product> q = cache.computeIfAbsent("SKU-404", sku -> Optional.ofNullable(repo.findOrNull(sku)));
// one database query; q is Optional.empty() from the cache
System.out.println(cache.containsKey("SKU-404")); // true
Null behaviour that changes in this migration
CallHashMapConcurrentHashMap / Map.copyOf
put(k, null)stores nullNullPointerException
get(null), containsKey(null)null / falseNullPointerException
Map.copyOf(map with null value)not applicableNullPointerException
merge(k, null, f)NullPointerExceptionNullPointerException
computeIfAbsent, f returns nullnothing storednothing stored

A cached negative result should usually expire sooner than a positive one, since the product may be created later. A real cache library such as Caffeine supports per-entry expiry and also treats a null from its loader as no entry, so the Optional pattern applies there too.

For the NullPointerExceptions, we decide at each boundary what absence means. A missing optional field might mean leave the key out of the map; a missing quantity might mean zero, so merge("apples", delta == null ? 0 : delta, Integer::sum). Lookups with a possibly-null key need a guard, key == null ? fallback : map.get(key). The decision is per field, which is why it needs a short audit of callers rather than a global search-and-replace.

6Testing the Null Paths Before Migrating

These bugs reached production because tests only used complete data. Before such a change, I would add tests that send requests with each optional field missing, look up keys that do not exist, and check that the second lookup of a missing key does not hit the repository again, which a mock or a call counter makes easy to assert. Running those tests against the old code first shows what behaviour we are preserving, and running them against the new code shows each place that needs a decision.

7Follow-up questions

Why does Map.copyOf reject nulls when HashMap allows them?

The immutable collections were designed later, with the view that nulls in collections cause more bugs than they solve. Rejecting them at creation means a Map.copyOf result is guaranteed null-free, and readers never need containsKey to interpret a null. The cost is that copying a map containing nulls fails, so the null has to be dealt with before copying.

Can computeIfAbsent cause other surprises on ConcurrentHashMap?

Yes. The mapping function runs while a part of the map is locked, so it should be short and must not modify the same map; a function that calls computeIfAbsent on the same map can throw IllegalStateException with a recursive update message, or deadlock in some cases. Slow work such as a remote call inside the function also blocks other writers to the same bin.

Is a sentinel object better than Optional?

Both work. Optional is self-explanatory and type-safe. A sentinel, such as a static final Product NOT_FOUND, avoids the wrapper allocation and keeps the map type unchanged, but every reader must remember to compare against it. For a cache of negative results, Optional is usually clearer.

8Conclusion

In this answer, we saw that the migration failed because ConcurrentHashMap, Map.copyOf and Map.of reject null keys and values, and even null queries, so code that stored or looked up nulls in a HashMap now throws NullPointerException inside map code. merge(key, null, f) throws in every Map, and computeIfAbsent stores nothing when the function returns null, so lookups with no result are recomputed every time. We fixed it by modelling absence explicitly with Optional values or a sentinel, by deciding at each boundary what a missing value means, and by testing the null paths before the migration.

What to say in the interviewAbout 100 seconds aloud

Open with

I think both problems come from null. HashMap accepts null keys and values, but ConcurrentHashMap rejects both, and Map.of and Map.copyOf are even stricter: they reject nulls at creation and throw on get(null) or containsKey(null).

Then, if they want more

So any request whose data has a null, like a missing optional field or a lookup that found nothing, now throws NullPointerException from inside putVal or the immutable collection classes, while requests with complete data work, which is why only some fail.

If the code also moved to merge, that throws for a null value in every Map implementation, because merge uses null to mean remove. The cache problem is computeIfAbsent's contract: if the mapping function returns null, no mapping is stored.

So every lookup for something that does not exist, say an unknown product, runs the function again and hits the database each time, and the cache seems to never store those keys. My fix is to model absence explicitly.

For the cache I would store Optional values, so a missing product is cached as Optional.empty, ideally with a shorter expiry, or use a sentinel object. For the other paths I would decide per field what absence means, for example zero for a missing quantity or leaving the key out, and guard lookups with possibly-null keys.

Before a migration like this I would write tests that exercise the null paths: missing fields, unknown keys, and a check that a second lookup of a missing key does not call the repository again.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A team replaced HashMap with ConcurrentHashMap and Map.copyOf in several places for...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/e18d423114/