Use ConcurrentHashMap for thread-safe operations on individual mappings, and use its atomic per-key methods when an action must combine a check with an update. A completed update for a key is visible to a non-null get that returns that updated value. But concurrent iteration and aggregate methods such as size() do not provide a stable snapshot of the whole map.
What ConcurrentHashMap guarantees
Oracle describes ConcurrentHashMap as a hash table with full concurrency of retrievals and high expected concurrency for updates. Retrievals such as get generally do not block and can overlap updates such as put and remove. A completed update for a key happens-before a non-null retrieval that reports that updated value, as specified in the Java SE 8 API.
This is not a transaction manager. Operations on different keys can interleave, and readers may observe only part of a multi-key change. The map also rejects null keys and null values.
Read and write mappings safely
For simple access, use get to retrieve the current value or null if the key is absent, and put or remove to update a mapping. When the operation depends on whether a mapping already exists, use a method that performs the check and update atomically:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteConcurrentHashMap<String, UserSession> sessions = new ConcurrentHashMap<>();
UserSession session = sessions.get(id);
// Insert only if absent; returns the existing or inserted value.
UserSession chosen = sessions.putIfAbsent(id, new UserSession());
// Create a value only when the key is absent.
UserSession loaded = sessions.computeIfAbsent(id, key -> loadSession(key));
// Replace or remove only if the current value matches the expected value.
sessions.replace(id, oldSession, refreshedSession);
sessions.remove(id, expectedSession);
Avoid separate check-and-act calls
This sequence is not atomic: if (!map.containsKey(k)) map.put(k, v). Another thread can insert or change the mapping between the check and the put. Use putIfAbsent for insert-if-missing behavior, or computeIfAbsent when the value should be created on demand.
Keep computation functions short and contained
The Java SE 26 API specifies that a computeIfAbsent invocation is atomic and invokes its mapping function once for that invocation when the key is absent. The function must not modify the same map during computation; recursive updates can throw IllegalStateException. Computation may also block other updates while it runs, so keep the function short and simple.
Rank #2
For a read-modify-write operation on an existing mapping, consider compute, computeIfPresent, or merge. These coordinate the remapping for the key. They do not make mutations inside a value object safe: if the mapped object has mutable fields, protect that state with an appropriate independent synchronization strategy.
Know what concurrent reads and iteration mean
Per-key visibility is not a whole-map snapshot
The happens-before guarantee applies to a retrieval that returns the updated value for the same key; it does not make a sequence of updates across multiple keys atomic. Concurrent retrievals can observe a putAll or clear only partly completed.
Iterators are weakly consistent
Iterators and spliterators from keySet(), values(), and entrySet() may reflect some changes made while traversal is in progress. They do not throw ConcurrentModificationException, but they are not stable, all-keys snapshots. They are intended for use by one iterator thread at a time. If a reader needs a consistent view of all keys and values, create a separate snapshot or coordinate access externally.
Aggregate methods are not transaction predicates
During concurrent updates, size(), isEmpty(), and containsValue() can reflect transient state. Java SE 8 documentation says these methods are typically useful only when the map is not undergoing concurrent updates in other threads. Treat them as diagnostics or approximate state during mutation, not as a basis for a lock-free check-and-act decision.
Rank #4
Use a concurrent counter value when counting
Oracle’s Java SE 8 API demonstrates a frequency map whose values are LongAdder instances:
ConcurrentHashMap<String, LongAdder> freqs = new ConcurrentHashMap<>();
freqs.computeIfAbsent(key, k -> new LongAdder()).increment();
computeIfAbsent handles creation of the per-key counter, while LongAdder is designed for concurrent updates. This pattern is useful when many threads update counts associated with different keys; it does not turn the map into a transactionally consistent multi-key structure.
Free tools Windows power users keep installed
One-click scans. No signup required.
Best Value
Use bulk operations without assuming an order
forEach, search, and reduce can process entries in parallel. The map is unordered, so functions must not depend on encounter order. Avoid relying on external state that may change while the computation runs; otherwise results can depend on timing as well as the entries being processed.
Quick Recap
Choose the right approach for the required guarantee
| Need | Approach | What it does not guarantee |
|---|---|---|
| Read one mapping | get(key) |
A snapshot of other keys or an atomic multi-key operation. |
| Insert only if absent | putIfAbsent or computeIfAbsent |
Short execution time if the mapping function is expensive; computation can delay other updates. |
| Update a mapping based on its current value | compute, computeIfPresent, or merge |
Thread safety for mutable state inside the value object. |
| Iterate while updates may occur | Use a weakly consistent view iterator | A fixed snapshot containing every mapping at one instant. |
| Make a decision based on the whole map | Build a snapshot or use external coordination | Consistency from aggregate methods alone while other threads mutate the map. |
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

