Skip to content

Commit

Permalink
Fix ReferencedKeySet::add
Browse files Browse the repository at this point in the history
  • Loading branch information
JimLaskey committed Mar 5, 2024
1 parent 51cf3e4 commit 7285991
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -439,4 +439,30 @@ private static <T> T internKey(ReferencedKeyMap<T, ReferenceKey<T>> setMap, T ke
return interned;
}


/**
* Attempt to add key to map if absent.
*
* @param setMap {@link ReferencedKeyMap} where interning takes place
* @param key key to add
*
* @param <T> type of key
*
* @return true if the key was added
*/
static <T> boolean internAddKey(ReferencedKeyMap<T, ReferenceKey<T>> setMap, T key) {
ReferenceKey<T> entryKey = setMap.entryKey(key);
setMap.removeStaleReferences();
ReferenceKey<T> existing = setMap.map.putIfAbsent(entryKey, entryKey);
if (existing == null) {
return true;
} else {
// If {@code putIfAbsent} returns non-null then was actually a
// {@code replace} and older key was used. In that case the new
// key was not used and the reference marked stale.
entryKey.unused();
return false;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public boolean contains(Object o) {

@Override
public boolean add(T e) {
return intern(e) == e;
return ReferencedKeyMap.internAddKey(map, e);
}

@Override
Expand Down
6 changes: 3 additions & 3 deletions test/jdk/jdk/internal/util/ReferencedKeyTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,10 @@ static void methods(ReferencedKeySet<Long> set) {
assertTrue(intern2 != null, "intern failed");
assertTrue(element3 == intern3, "intern failed");

Long value1 = new Long(BASE_KEY + 999);
Long value2 = new Long(BASE_KEY + 999);
Long value1 = Long.valueOf(BASE_KEY + 999);
Long value2 = Long.valueOf(BASE_KEY + 999);
assertTrue(set.add(value1), "key not added");
assertTrue(set.add(value1), "key not added after second attempt");
assertTrue(!set.add(value1), "key added after second attempt");
assertTrue(!set.add(value2), "key should not have been added");
}

Expand Down

0 comments on commit 7285991

Please sign in to comment.