1 19 package org.objectweb.carol.cmi; 20 21 import java.lang.ref.WeakReference ; 22 import java.lang.ref.ReferenceQueue ; 23 24 28 public class WeakCache { 29 private java.util.HashMap table = new java.util.HashMap (); 30 31 private class WeakRef extends WeakReference { 32 private int hash; 33 34 public WeakRef(Object obj) { 35 super(obj); 36 hash = obj.hashCode(); 37 } 38 39 public WeakRef(Object obj, ReferenceQueue rq) { 40 super(obj, rq); 41 hash = obj.hashCode(); 42 } 43 44 public int hashCode() { 45 return hash; 46 } 47 48 public boolean equals(Object obj) { 49 if (obj == this) { 51 return true; 52 } 53 54 if (obj instanceof WeakRef) { 55 Object o = this.get(); 56 return (o != null) && o.equals(((WeakRef) obj).get()); 57 } else 58 return false; 59 } 60 61 public void remove() { 62 synchronized (table) { 63 table.remove(this); 64 } 65 } 66 } 67 68 private static ReferenceQueue rQueue = new ReferenceQueue (); 69 private static Thread rQueueThread = new RefQueueFlush(); 70 static { 71 rQueueThread.setDaemon(true); 72 rQueueThread.start(); 73 } 74 75 private static class RefQueueFlush extends Thread { 76 public RefQueueFlush() { 77 } 78 public void run() { 79 while (true) { 80 try { 81 WeakRef wr = (WeakRef) rQueue.remove(); 82 wr.remove(); 83 } catch (InterruptedException e) { 84 } 86 } 87 } 88 } 89 90 95 public Object getCached(Object obj) { 96 WeakRef wr = new WeakRef(obj, rQueue); 97 synchronized (table) { 98 WeakRef cached = (WeakRef) table.get(wr); 99 if (cached == null) { 100 table.put(wr, wr); 101 return obj; 102 } 103 Object c = cached.get(); 104 if (c == null) { 105 table.remove(cached); 106 table.put(wr, wr); 107 return obj; 108 } 109 return c; 110 } 111 } 112 } 113 | Popular Tags |