mirror of https://github.com/apache/lucene.git
LUCENE-1257: Generify CloseableThreadLocal
git-svn-id: https://svn.apache.org/repos/asf/lucene/java/trunk@826532 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
parent
504cd94c0b
commit
501d8c59e4
|
@ -42,20 +42,20 @@ import java.lang.ref.WeakReference;
|
||||||
* references are cleared and then GC is freely able to
|
* references are cleared and then GC is freely able to
|
||||||
* reclaim space by objects stored in it. */
|
* reclaim space by objects stored in it. */
|
||||||
|
|
||||||
public class CloseableThreadLocal {
|
public class CloseableThreadLocal<T> {
|
||||||
|
|
||||||
private ThreadLocal t = new ThreadLocal();
|
private ThreadLocal<WeakReference<T>> t = new ThreadLocal<WeakReference<T>>();
|
||||||
|
|
||||||
private Map hardRefs = new HashMap();
|
private Map<Thread,T> hardRefs = new HashMap<Thread,T>();
|
||||||
|
|
||||||
protected Object initialValue() {
|
protected T initialValue() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Object get() {
|
public T get() {
|
||||||
WeakReference weakRef = (WeakReference) t.get();
|
WeakReference<T> weakRef = t.get();
|
||||||
if (weakRef == null) {
|
if (weakRef == null) {
|
||||||
Object iv = initialValue();
|
T iv = initialValue();
|
||||||
if (iv != null) {
|
if (iv != null) {
|
||||||
set(iv);
|
set(iv);
|
||||||
return iv;
|
return iv;
|
||||||
|
@ -66,17 +66,16 @@ public class CloseableThreadLocal {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void set(Object object) {
|
public void set(T object) {
|
||||||
|
|
||||||
t.set(new WeakReference(object));
|
t.set(new WeakReference<T>(object));
|
||||||
|
|
||||||
synchronized(hardRefs) {
|
synchronized(hardRefs) {
|
||||||
hardRefs.put(Thread.currentThread(), object);
|
hardRefs.put(Thread.currentThread(), object);
|
||||||
|
|
||||||
// Purge dead threads
|
// Purge dead threads
|
||||||
Iterator it = hardRefs.keySet().iterator();
|
for (Iterator<Thread> it = hardRefs.keySet().iterator(); it.hasNext();) {
|
||||||
while(it.hasNext()) {
|
final Thread t = it.next();
|
||||||
Thread t = (Thread) it.next();
|
|
||||||
if (!t.isAlive())
|
if (!t.isAlive())
|
||||||
it.remove();
|
it.remove();
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue