Skip to content

Commit a648173

Browse files
committed
Fix race condition in Fraction.hashCode()
1 parent 4a021ec commit a648173

2 files changed

Lines changed: 3 additions & 5 deletions

File tree

src/changes/changes.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ The <action> type attribute can be add,update,fix,remove.
7474
<action type="fix" dev="ggregory" due-to="David Du, Gary Gregory">Remove redundant length check in StringUtils.isBlank(CharSequence) #1516.</action>
7575
<action issue="LANG-1800" type="fix" dev="ggregory" due-to="IcoreE">Incorrect grammar and unclear wording in RandomStringUtils#random method #1520.</action>
7676
<action issue="LANG-1802" type="fix" dev="ggregory" due-to="Gary Gregory, IcoreE">Fix collision in CharRange.hashCode().</action>
77+
<action type="fix" dev="ggregory" due-to="Gary Gregory">Fix race condition in Fraction.hashCode().</action>
7778
<!-- ADD -->
7879
<!-- UPDATE -->
7980
<action type="update" dev="ggregory" due-to="Gary Gregory, Dependabot">Bump org.apache.commons:commons-parent from 92 to 93 #1498.</action>

src/main/java/org/apache/commons/lang3/math/Fraction.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ private static int subAndCheck(final int x, final int y) {
467467
/**
468468
* Cached output hashCode (class is immutable).
469469
*/
470-
private transient int hashCode;
470+
private final int hashCode;
471471

472472
/**
473473
* Cached output toString (class is immutable).
@@ -489,6 +489,7 @@ private static int subAndCheck(final int x, final int y) {
489489
private Fraction(final int numerator, final int denominator) {
490490
this.numerator = numerator;
491491
this.denominator = denominator;
492+
this.hashCode = Objects.hash(denominator, numerator);
492493
}
493494

494495
/**
@@ -720,10 +721,6 @@ public int getProperWhole() {
720721
*/
721722
@Override
722723
public int hashCode() {
723-
if (hashCode == 0) {
724-
// hash code update should be atomic.
725-
hashCode = Objects.hash(denominator, numerator);
726-
}
727724
return hashCode;
728725
}
729726

0 commit comments

Comments
 (0)