下面列出了怎么用java.lang.ref.ReferenceQueue的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void run() {
try {
while (true) {
ReferenceQueue<V> q = getQueue();
if (q == null)
break; // soft cache deallocated -- stop the thread
if (q.remove(10000) == null)
continue; // was there something deallocated?
while (q.poll() != null) {
} // pull all the deallocated references from the queue
cleanDeallocated(); // clean the cache
}
sLogger.debug("cache terminated");
} catch (Exception e) {
sLogger.error("cleanup thread failed, reason:" + e.getMessage(), e);
}
}
Segment(
LocalCache<K, V> map,
int initialCapacity,
long maxSegmentWeight,
StatsCounter statsCounter) {
this.map = map;
this.maxSegmentWeight = maxSegmentWeight;
this.statsCounter = checkNotNull(statsCounter);
initTable(newEntryArray(initialCapacity));
keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<K>() : null;
valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<V>() : null;
recencyQueue = map.usesAccessQueue()
? new ConcurrentLinkedQueue<ReferenceEntry<K, V>>()
: LocalCache.<ReferenceEntry<K, V>>discardingQueue();
writeQueue =
map.usesWriteQueue()
? new WriteQueue<K, V>()
: LocalCache.<ReferenceEntry<K, V>>discardingQueue();
accessQueue =
map.usesAccessQueue()
? new AccessQueue<K, V>()
: LocalCache.<ReferenceEntry<K, V>>discardingQueue();
}
public ElasticsearchStore(String hostname, int port, String clusterName, String index, boolean cacheEnabled) {
super(cacheEnabled);
this.hostname = hostname;
this.port = port;
this.clusterName = clusterName;
this.index = index;
clientProvider = new SingletonClientProvider(hostname, port, clusterName);
dataStructure = new ElasticsearchDataStructure(clientProvider, index);
namespaceStore = new ElasticsearchNamespaceStore(clientProvider, index + "_namespaces");
ReferenceQueue<ElasticsearchStore> objectReferenceQueue = new ReferenceQueue<>();
startGarbageCollectionMonitoring(objectReferenceQueue, new PhantomReference<>(this, objectReferenceQueue),
clientProvider);
}
public static void main(String[] args) throws InterruptedException{
Thread t=new CheckRefQueue();
t.setDaemon(true);
t.start();
User u=new User(1,"chenyang");
softQueue=new ReferenceQueue<User>();
UserSoftReference userSoftRef=new UserSoftReference(u,softQueue);
u=null;
System.out.println(userSoftRef.get());
System.gc();
System.out.println("After GC:");
System.out.println(userSoftRef.get());
System.out.println("try to create byte array and GC");
byte[] b=new byte[1024*925*7];
System.gc();
System.out.println(userSoftRef.get());
Thread.sleep(1000);
}
private static void runTest(int compression) throws Exception {
ReferenceQueue<InputStream> rq = new ReferenceQueue<>();
System.out.println("Testing with a zip file with compression level = "
+ compression);
File f = createTestFile(compression);
try (ZipFile zf = new ZipFile(f)) {
Set<Object> refSet = createTransientInputStreams(zf, rq);
System.out.println("Waiting for 'stale' input streams from ZipFile to be GC'd ...");
System.out.println("(The test will hang on failure)");
while (false == refSet.isEmpty()) {
refSet.remove(rq.remove());
}
System.out.println("Test PASSED.");
System.out.println();
} finally {
f.delete();
}
}
private static ReferenceQueue<JComponent> getQueue() {
synchronized(ActionPropertyChangeListener.class) {
if (queue == null) {
queue = new ReferenceQueue<JComponent>();
}
}
return queue;
}
public static final void main(String[] args) throws Exception {
System.err.println("\n Regression test for bug 6232010\n");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
ClassLoader loader = new URLClassLoader(((URLClassLoader) systemLoader).getURLs(),
systemLoader.getParent());
Class<? extends ObjectOutputStream> cl =
Class.forName(SubclassOfOOS.class.getName(), false,
loader).asSubclass(ObjectOutputStream.class);
Constructor<? extends ObjectOutputStream> cons =
cl.getConstructor(OutputStream.class);
OutputStream os = new ByteArrayOutputStream();
ObjectOutputStream obj = cons.newInstance(os);
final ReferenceQueue<Class<?>> queue = new ReferenceQueue<Class<?>>();
WeakReference<Class<?>> ref = new WeakReference<Class<?>>(cl, queue);
cl = null;
obj = null;
loader = null;
cons = null;
systemLoader = null;
System.err.println("\nStart Garbage Collection right now");
System.gc();
Reference<? extends Class<?>> dequeued = queue.remove(TIMEOUT);
if (dequeued == ref) {
System.err.println("\nTEST PASSED");
} else {
throw new Error();
}
}
/**
* Gets the active reference queue.
* @return the singleton queue
*/
public static synchronized ReferenceQueue<Object> queue() {
if (activeReferenceQueue == null) {
activeReferenceQueue = new Impl();
Daemon.ping();
}
return activeReferenceQueue;
}
public ProcessorKeeper21(boolean useWeakRefs) {
this.useWeakRefs = useWeakRefs;
//should I use private construtor or this is fine
if(useWeakRefs) {
processorIdReferenceQueue = new ReferenceQueue();
synchronized (cleanupAllProcessKeepers) {
cleanupAllProcessKeepers.add(this);
}
} else {
processorIdReferenceQueue = null;
}
}
/**
* Removes weak keys from the map that have been enqueued
* on the reference queue and are no longer in use.
*/
private static void processQueue(ReferenceQueue<Key> queue,
ConcurrentHashMap<? extends
WeakReference<Key>, ?> pdMap) {
Reference<? extends Key> ref;
while ((ref = queue.poll()) != null) {
pdMap.remove(ref);
}
}
public PixelCountSoftReference(Image referent, ReferenceQueue<? super Image> q, int pixelCount, int hash,
GraphicsConfiguration config, int w, int h, Object[] args) {
super(referent, q);
this.pixelCount = pixelCount;
this.hash = hash;
this.config = config;
this.w = w;
this.h = h;
this.args = args;
}
FieldReflectorKey(Class<?> cl, ObjectStreamField[] fields,
ReferenceQueue<Class<?>> queue)
{
super(cl, queue);
nullClass = (cl == null);
sigs = new String[2 * fields.length];
for (int i = 0, j = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i];
sigs[j++] = f.getName();
sigs[j++] = f.getSignature();
}
hash = System.identityHashCode(cl) + Arrays.hashCode(sigs);
}
protected SwitchableSoftReference( T pReferent,
ReferenceQueue<T> pReferenceQueue,
Runnable pCleaningRunnable)
{
super(pReferent, pReferenceQueue);
mHardReference = pReferent;
mCleaningRunnable = pCleaningRunnable;
}
/**
* Starts the Finalizer thread. FinalizableReferenceQueue calls this method reflectively.
*
* @param finalizableReferenceClass FinalizableReference.class.
* @param queue a reference queue that the thread will poll.
* @param frqReference a phantom reference to the FinalizableReferenceQueue, which will be queued
* either when the FinalizableReferenceQueue is no longer referenced anywhere, or when its
* close() method is called.
*/
public static void startFinalizer(
Class<?> finalizableReferenceClass,
ReferenceQueue<Object> queue,
PhantomReference<Object> frqReference) {
/*
* We use FinalizableReference.class for two things:
*
* 1) To invoke FinalizableReference.finalizeReferent()
*
* 2) To detect when FinalizableReference's class loader has to be garbage collected, at which
* point, Finalizer can stop running
*/
if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) {
throw new IllegalArgumentException("Expected " + FINALIZABLE_REFERENCE + ".");
}
Finalizer finalizer = new Finalizer(finalizableReferenceClass, queue, frqReference);
Thread thread = new Thread(finalizer);
thread.setName(Finalizer.class.getName());
thread.setDaemon(true);
try {
if (inheritableThreadLocals != null) {
inheritableThreadLocals.set(thread, null);
}
} catch (Throwable t) {
logger.log(
Level.INFO,
"Failed to clear thread local values inherited by reference finalizer thread.",
t);
}
thread.start();
}
static <K> Object valueOf(K key, ReferenceQueue<K> refQueue) {
return key == null
// null key means we can't weakly reference it,
// so we use a NULL_KEY singleton as cache key
? NULL_KEY
// non-null key requires wrapping with a WeakReference
: new CacheKey<>(key, refQueue);
}
public WeakEntry(Object key, ReferenceQueue queue,
int hash, Entry next)
{
super(key, queue);
this.hash = hash;
this.next = next;
}
private static ReferenceQueue<JComponent> getQueue() {
synchronized(ActionPropertyChangeListener.class) {
if (queue == null) {
queue = new ReferenceQueue<JComponent>();
}
}
return queue;
}
public WeakEntry(CachedQuery key, ReferenceQueue queue,
int hash, Entry next)
{
super(key, queue);
this.hash = hash;
this.next = next;
}
AbstractChangeHandler(DefaultStyledDocument d) {
Class c = getClass();
ReferenceQueue<DefaultStyledDocument> q;
synchronized (queueMap) {
q = queueMap.get(c);
if (q == null) {
q = new ReferenceQueue<DefaultStyledDocument>();
queueMap.put(c, q);
}
}
doc = new DocReference(d, q);
}
ConnectionPhantomReference(ConnectionImpl connectionImpl, ReferenceQueue<ConnectionImpl> q) {
super(connectionImpl, q);
try {
this.io = connectionImpl.getIO().getNetworkResources();
} catch (SQLException e) {
// if we somehow got here and there's really no i/o, we deal with it later
}
}
static <K> Object valueOf(K key, ReferenceQueue<K> refQueue) {
return key == null
// null key means we can't weakly reference it,
// so we use a NULL_KEY singleton as cache key
? NULL_KEY
// non-null key requires wrapping with a WeakReference
: new CacheKey<>(key, refQueue);
}
PhantomDelegatingCloseableRef(
WrappingProxyCloseable<? extends Closeable> referent,
SafetyNetCloseableRegistry closeableRegistry,
ReferenceQueue<? super WrappingProxyCloseable<? extends Closeable>> q) {
super(referent, q);
this.innerCloseable = Preconditions.checkNotNull(WrappingProxyUtil.stripProxy(referent));
this.closeableRegistry = Preconditions.checkNotNull(closeableRegistry);
this.debugString = referent.toString();
}
public static final void main(String[] args) throws Exception {
System.err.println("\n Regression test for bug 6232010\n");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
ClassLoader loader = new URLClassLoader(((URLClassLoader) systemLoader).getURLs(),
systemLoader.getParent());
Class<? extends ObjectOutputStream> cl =
Class.forName(SubclassOfOOS.class.getName(), false,
loader).asSubclass(ObjectOutputStream.class);
Constructor<? extends ObjectOutputStream> cons =
cl.getConstructor(OutputStream.class);
OutputStream os = new ByteArrayOutputStream();
ObjectOutputStream obj = cons.newInstance(os);
final ReferenceQueue<Class<?>> queue = new ReferenceQueue<Class<?>>();
WeakReference<Class<?>> ref = new WeakReference<Class<?>>(cl, queue);
cl = null;
obj = null;
loader = null;
cons = null;
systemLoader = null;
System.err.println("\nStart Garbage Collection right now");
System.gc();
Reference<? extends Class<?>> dequeued = queue.remove(TIMEOUT);
if (dequeued == ref) {
System.err.println("\nTEST PASSED");
} else {
throw new Error();
}
}
final Object newKeyReference(K key, ReferenceType keyType,
ReferenceQueue<Object> refQueue) {
if (keyType == ReferenceType.WEAK)
return new WeakKeyReference<K>(key, hash, refQueue);
if (keyType == ReferenceType.SOFT)
return new SoftKeyReference<K>(key, hash, refQueue);
return key;
}
public PixelCountSoftReference(Image referent, ReferenceQueue<? super Image> q, int pixelCount, int hash,
GraphicsConfiguration config, int w, int h, Object[] args) {
super(referent, q);
this.pixelCount = pixelCount;
this.hash = hash;
this.config = config;
this.w = w;
this.h = h;
this.args = args;
}
@Override
public Entry cloneWithNext(ReferenceQueue queue, Entry next)
{
if (this.next == next)
{
return this;
}
return new WeakEntry(this.get(), queue, this.hash, next);
}
final Object newKeyReference(K key, ReferenceType keyType,
ReferenceQueue<Object> refQueue) {
if (keyType == ReferenceType.WEAK)
return new WeakKeyReference<K>(key, hash, refQueue);
if (keyType == ReferenceType.SOFT)
return new SoftKeyReference<K>(key, hash, refQueue);
return key;
}
public PixelCountSoftReference(Image referent, ReferenceQueue<? super Image> q, int pixelCount, int hash,
GraphicsConfiguration config, int w, int h, Object[] args) {
super(referent, q);
this.pixelCount = pixelCount;
this.hash = hash;
this.config = config;
this.w = w;
this.h = h;
this.args = args;
}
WeakValueReference(V value, Object keyRef, int hash, ReferenceQueue<Object> refQueue) {
super(value, refQueue);
this.keyRef = keyRef;
this.hash = hash;
}
private static ReferenceQueue<Object> activeQueue() {
return ActiveQueue.queue();
}