diff --git a/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java b/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java index 7e3cb33c2..ad258a061 100644 --- a/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java +++ b/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java @@ -118,7 +118,7 @@ public class HashCodeBuilder implements Builder { * * @since 2.3 */ - private static final ThreadLocal> REGISTRY = new ThreadLocal<>(); + private static final ThreadLocal> REGISTRY = ThreadLocal.withInitial(HashSet::new); /* * NOTE: we cannot store the actual objects in a HashSet, as that would use the very hashCode() @@ -467,12 +467,7 @@ public class HashCodeBuilder implements Builder { * The object to register. */ private static void register(final Object value) { - Set registry = getRegistry(); - if (registry == null) { - registry = new HashSet<>(); - REGISTRY.set(registry); - } - registry.add(new IDKey(value)); + getRegistry().add(new IDKey(value)); } /** @@ -480,6 +475,7 @@ public class HashCodeBuilder implements Builder { * *

* Used by the reflection methods to avoid infinite loops. + *

* * @param value * The object to unregister. @@ -487,11 +483,9 @@ public class HashCodeBuilder implements Builder { */ private static void unregister(final Object value) { final Set registry = getRegistry(); - if (registry != null) { - registry.remove(new IDKey(value)); - if (registry.isEmpty()) { - REGISTRY.remove(); - } + registry.remove(new IDKey(value)); + if (registry.isEmpty()) { + REGISTRY.remove(); } } diff --git a/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java b/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java index e1361b9c7..10bacf13b 100644 --- a/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java @@ -19,8 +19,8 @@ package org.apache.commons.lang3.builder; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.commons.lang3.AbstractLangTest; import org.junit.jupiter.api.Test; @@ -563,9 +563,9 @@ public class HashCodeBuilderTest extends AbstractLangTest { // at org.apache.commons.lang.builder.HashCodeBuilder.append(HashCodeBuilder.java:422) a.hashCode(); - assertNull(HashCodeBuilder.getRegistry()); + assertTrue(HashCodeBuilder.getRegistry().isEmpty()); b.hashCode(); - assertNull(HashCodeBuilder.getRegistry()); + assertTrue(HashCodeBuilder.getRegistry().isEmpty()); } @Test