void (Map<? super String, Object> map) { String key = "a"; map.put(key, new Object()); String newVal = "xxx"; int i; int N = 1_000_000; for (i = 0; i < N; i++) { Object prev = map.putIfAbsent(key, newVal); if (prev == null) { assertSame(newVal, map.get(key)); break; } assertEquals(Object.class, prev.getClass()); Object actual = map.get(key); assertNotNull(actual); if (actual == newVal) { break; // gced, replaced } assertEquals(Object.class, actual.getClass()); // still not gced, put failed. repeat } if (i == N) { GCUtil.tryGcSoftlyReachableObjects(() -> map.get(key)==null); Object prev = map.putIfAbsent(key, newVal); assertNull(prev); assertSame(newVal, map.get(key)); } }