From b88b6a73ad19b9dd65bde1d78a45b4edc576fbd0 Mon Sep 17 00:00:00 2001 From: Michael McCandless Date: Tue, 16 Sep 2008 14:24:17 +0000 Subject: [PATCH] LUCENE-1388: add initialValue() method to CloseableThreadLocal git-svn-id: https://svn.apache.org/repos/asf/lucene/java/trunk@695899 13f79535-47bb-0310-9956-ffa450edef68 --- .../lucene/util/CloseableThreadLocal.java | 19 +++++++++++++----- .../index/TestCloseableThreadLocal.java | 20 +++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) create mode 100644 src/test/org/apache/lucene/index/TestCloseableThreadLocal.java diff --git a/src/java/org/apache/lucene/util/CloseableThreadLocal.java b/src/java/org/apache/lucene/util/CloseableThreadLocal.java index 23fe527b327..b936c56c3b3 100644 --- a/src/java/org/apache/lucene/util/CloseableThreadLocal.java +++ b/src/java/org/apache/lucene/util/CloseableThreadLocal.java @@ -42,17 +42,26 @@ import java.lang.ref.WeakReference; * references are cleared and then GC is freely able to * reclaim space by objects stored in it. */ -public final class CloseableThreadLocal { +public class CloseableThreadLocal { private ThreadLocal t = new ThreadLocal(); private Map hardRefs = new HashMap(); - + + protected Object initialValue() { + return null; + } + public Object get() { WeakReference weakRef = (WeakReference) t.get(); - if (weakRef == null) - return null; - else { + if (weakRef == null) { + Object iv = initialValue(); + if (iv != null) { + set(iv); + return iv; + } else + return null; + } else { Object v = weakRef.get(); // This can never be null, because we hold a hard // reference to the underlying object: diff --git a/src/test/org/apache/lucene/index/TestCloseableThreadLocal.java b/src/test/org/apache/lucene/index/TestCloseableThreadLocal.java new file mode 100644 index 00000000000..3a37603d66e --- /dev/null +++ b/src/test/org/apache/lucene/index/TestCloseableThreadLocal.java @@ -0,0 +1,20 @@ +package org.apache.lucene.index; + +import org.apache.lucene.util.CloseableThreadLocal; +import org.apache.lucene.util.LuceneTestCase; + +public class TestCloseableThreadLocal extends LuceneTestCase { + public static final String TEST_VALUE = "initvaluetest"; + + public void testInitValue() { + InitValueThreadLocal tl = new InitValueThreadLocal(); + String str = (String)tl.get(); + assertEquals(TEST_VALUE, str); + } + + public class InitValueThreadLocal extends CloseableThreadLocal { + protected Object initialValue() { + return TEST_VALUE; + } + } +}