Skip to content

Commit a7461de

Browse files
author
Jim Laskey
committed
8325255: jdk.internal.util.ReferencedKeySet::add using wrong test
Reviewed-by: rriggs, liach
1 parent 2bdd387 commit a7461de

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

src/java.base/share/classes/jdk/internal/util/ReferencedKeyMap.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,4 +439,30 @@ private static <T> T internKey(ReferencedKeyMap<T, ReferenceKey<T>> setMap, T ke
439439
return interned;
440440
}
441441

442+
443+
/**
444+
* Attempt to add key to map if absent.
445+
*
446+
* @param setMap {@link ReferencedKeyMap} where interning takes place
447+
* @param key key to add
448+
*
449+
* @param <T> type of key
450+
*
451+
* @return true if the key was added
452+
*/
453+
static <T> boolean internAddKey(ReferencedKeyMap<T, ReferenceKey<T>> setMap, T key) {
454+
ReferenceKey<T> entryKey = setMap.entryKey(key);
455+
setMap.removeStaleReferences();
456+
ReferenceKey<T> existing = setMap.map.putIfAbsent(entryKey, entryKey);
457+
if (existing == null) {
458+
return true;
459+
} else {
460+
// If {@code putIfAbsent} returns non-null then was actually a
461+
// {@code replace} and older key was used. In that case the new
462+
// key was not used and the reference marked stale.
463+
entryKey.unused();
464+
return false;
465+
}
466+
}
467+
442468
}

src/java.base/share/classes/jdk/internal/util/ReferencedKeySet.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ public boolean contains(Object o) {
148148

149149
@Override
150150
public boolean add(T e) {
151-
return intern(e) == null;
151+
return ReferencedKeyMap.internAddKey(map, e);
152152
}
153153

154154
@Override

test/jdk/jdk/internal/util/ReferencedKeyTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,12 @@ static void methods(ReferencedKeySet<Long> set) {
127127
assertTrue(element1 == intern1, "intern failed"); // must be same object
128128
assertTrue(intern2 != null, "intern failed");
129129
assertTrue(element3 == intern3, "intern failed");
130+
131+
Long value1 = Long.valueOf(BASE_KEY + 999);
132+
Long value2 = Long.valueOf(BASE_KEY + 999);
133+
assertTrue(set.add(value1), "key not added");
134+
assertTrue(!set.add(value1), "key added after second attempt");
135+
assertTrue(!set.add(value2), "key should not have been added");
130136
}
131137

132138
// Borrowed from jdk.test.lib.util.ForceGC but couldn't use from java.base/jdk.internal.util

0 commit comments

Comments
 (0)