ConcurrentHashMap forEach Entry Actions
Walk a ConcurrentHashMap with forEach entry actions and keySet views, relying on weakly consistent iteration instead of snapshots.
Code
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class ConcurrentWalk {
public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap<String, Integer> stock = new ConcurrentHashMap<>();
stock.put("widget", 40);
stock.put("gadget", 7);
stock.put("doohickey", 0);
// forEach(parallelismThreshold, action):弱一致性遍历,
// 不抛 ConcurrentModificationException,但不保证看到遍历开始后的 put
stock.forEach(10, (key, qty) ->
System.out.println(key + " = " + qty));
// forEachEntry 直接在 Entry 上操作,避免二次查找
AtomicInteger outOfStock = new AtomicInteger();
stock.forEachEntry(1, entry -> {
if (entry.getValue() == 0) {
outOfStock.incrementAndGet();
System.out.println("out of stock: " + entry.getKey());
}
});
System.out.println("out-of-stock count: " + outOfStock.get());
// 遍历中并发写入是安全的:这次写入是否出现在下一次遍历里不承诺
Thread writer = new Thread(() -> stock.put("sprocket", 3));
writer.start();
writer.join();
System.out.println("mappingCount after write: " + stock.mappingCount());
System.out.println("keySet contains sprocket: " + stock.keySet().contains("sprocket"));
}
}What runs, in order
ConcurrentHashMap forEach Entry Actions comes down to the class ConcurrentWalk.
Caveats
- No dependencies section needed; the standard library is the whole story.
Using it
Watch for these markers — out of stock:, out-of-stock count:, mappingCount after write: — when the file runs.
Lines worth quoting
Thread writer = new Thread(() -> stock.put("sprocket", 3));
Interactive Tools for This Topic
FAQ
- What does ConcurrentHashMap forEach Entry Actions print when run?
- The script runs standalone; its 4 labeled outputs include `out of stock:`, `out-of-stock count:`, `mappingCount after write:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.