From 1f35e7c99b66b8d46c4ad96558e694a10aa38062 Mon Sep 17 00:00:00 2001 From: Matthew Jason Benson Date: Sun, 7 Feb 2010 03:14:09 +0000 Subject: [PATCH] [LANG-586] Clear ThreadLocal for HashCodeBuilder as well git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@907373 13f79535-47bb-0310-9956-ffa450edef68 --- .../lang3/builder/HashCodeBuilder.java | 29 ++++++++++++------- .../lang3/builder/HashCodeBuilderTest.java | 2 ++ 2 files changed, 20 insertions(+), 11 deletions(-) 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 547676ccb..9f7e8903b 100644 --- a/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java +++ b/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java @@ -101,14 +101,7 @@ public class HashCodeBuilder { * * @since 2.3 */ - private static final ThreadLocal> registry = new ThreadLocal>() { - @Override - protected Set initialValue() { - // The HashSet implementation is not synchronized, - // which is just what we need here. - return new HashSet(); - } - }; + private static final ThreadLocal> REGISTRY = new ThreadLocal>(); /* * N.B. we cannot store the actual objects in a HashSet, as that would use the very hashCode() @@ -136,7 +129,7 @@ protected Set initialValue() { * @since 2.3 */ static Set getRegistry() { - return registry.get(); + return REGISTRY.get(); } /** @@ -151,7 +144,8 @@ static Set getRegistry() { * @since 2.3 */ static boolean isRegistered(Object value) { - return getRegistry().contains(new IDKey(value)); + Set registry = getRegistry(); + return registry != null && registry.contains(new IDKey(value)); } /** @@ -521,6 +515,11 @@ public static int reflectionHashCode(Object object, String[] excludeFields) { * The object to register. */ static void register(Object value) { + synchronized (HashCodeBuilder.class) { + if (getRegistry() == null) { + REGISTRY.set(new HashSet()); + } + } getRegistry().add(new IDKey(value)); } @@ -537,7 +536,15 @@ static void register(Object value) { * @since 2.3 */ static void unregister(Object value) { - getRegistry().remove(new IDKey(value)); + Set s = getRegistry(); + if (s != null) { + s.remove(new IDKey(value)); + synchronized (HashCodeBuilder.class) { + if (s.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 f6af5f035..64b34f907 100644 --- a/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java +++ b/src/test/java/org/apache/commons/lang3/builder/HashCodeBuilderTest.java @@ -521,7 +521,9 @@ public void testReflectionObjectCycle() { // at org.apache.commons.lang.builder.HashCodeBuilder.append(HashCodeBuilder.java:422) a.hashCode(); + assertNull(HashCodeBuilder.getRegistry()); b.hashCode(); + assertNull(HashCodeBuilder.getRegistry()); } /**