mirror of https://github.com/apache/lucene.git
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
This commit is contained in:
parent
9d23731bea
commit
b88b6a73ad
|
@ -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)
|
||||
if (weakRef == null) {
|
||||
Object iv = initialValue();
|
||||
if (iv != null) {
|
||||
set(iv);
|
||||
return iv;
|
||||
} else
|
||||
return null;
|
||||
else {
|
||||
} else {
|
||||
Object v = weakRef.get();
|
||||
// This can never be null, because we hold a hard
|
||||
// reference to the underlying object:
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue