Skip to content

Commit

Permalink
Fix issues with ArrayTagSet's hashCode
Browse files Browse the repository at this point in the history
- Only read cached hash code field once to avoid running afoul of edge case involving
  re-ordering of operations permitted by the Java memory model.
- Make computed hash code consistent with Arrays.hashCode (e.g., ArrayTagSet.EMPTY hashes to 1).
  • Loading branch information
kilink committed Oct 5, 2022
1 parent 3609f16 commit 14446fe
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -467,14 +467,15 @@ private static int dedupInPlace(String[] data, int len) {
}

@Override public int hashCode() {
if (cachedHashCode == 0) {
int result = length;
int hc = cachedHashCode;
if (hc == 0) {
hc = 1;
for (int i = 0; i < length; ++i) {
result = 31 * result + tags[i].hashCode();
hc = 31 * hc + tags[i].hashCode();
}
cachedHashCode = result;
cachedHashCode = hc;
}
return cachedHashCode;
return hc;
}

@Override public String toString() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ public void equalsContractTest() {
Assertions.assertEquals(ts2, ArrayTagSet.create("k2", "v2").addAll(ArrayTagSet.create("k1", "v1")));
}

@Test
public void testHashCode() {
Assertions.assertEquals(1, ArrayTagSet.EMPTY.hashCode());
Assertions.assertEquals(ArrayTagSet.create("k1", "v1", "k2", "v2"), ArrayTagSet.create("k2", "v2", "k1", "v1"));
}

@Test
public void testToString() {
ArrayTagSet ts1 = ArrayTagSet.create("k1", "v1");
Expand Down

0 comments on commit 14446fe

Please sign in to comment.