java.lang.ref.PhantomReference Java Examples
The following examples show how to use
java.lang.ref.PhantomReference.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PhantomReferenceDemo.java From code with Apache License 2.0 | 6 votes |
/** * 虚引用 * 虚引用用来跟踪对象被垃圾回收器回收的活动。虚引用和软引用与弱引用的区别在于虚引用必须和引用队列联合使用, * 当虚引用被加入到引用队列的时候,说明这个对象已经被回收,可以在所引用的对象回收之后可以采取必要的行动。 */ public static void main(String[] args) throws InterruptedException { Object o = new Object(); // 必须结合引用队列 ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>(); // 虚引用 PhantomReference<Object> phantomReference = new PhantomReference<>(o, referenceQueue); System.out.println(o); System.out.println(phantomReference.get()); System.out.println(referenceQueue.poll()); System.out.println("================="); o = null; System.gc(); Thread.sleep(500); System.out.println(o); System.out.println(phantomReference.get()); System.out.println(referenceQueue.poll()); }
Example #2
Source File: CleanerTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Test that releasing the reference to the Cleaner service allows it to be * be freed. */ @Test void testCleanerTermination() { ReferenceQueue<Object> queue = new ReferenceQueue<>(); Cleaner service = Cleaner.create(); PhantomReference<Object> ref = new PhantomReference<>(service, queue); System.gc(); // Clear the Reference to the cleaning service and force a gc. service = null; System.gc(); try { Reference<?> r = queue.remove(1000L); Assert.assertNotNull(r, "queue.remove timeout,"); Assert.assertEquals(r, ref, "Wrong Reference dequeued"); } catch (InterruptedException ie) { System.out.printf("queue.remove Interrupted%n"); } }
Example #3
Source File: FinalizableReferenceQueue.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Constructs a new queue. */ public FinalizableReferenceQueue() { // We could start the finalizer lazily, but I'd rather it blow up early. queue = new ReferenceQueue<Object>(); frqRef = new PhantomReference<Object>(this, queue); boolean threadStarted = false; try { startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef); threadStarted = true; } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // startFinalizer() is public } catch (Throwable t) { logger.log(Level.INFO, "Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are created.", t); } this.threadStarted = threadStarted; }
Example #4
Source File: CleanerTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Create a CleanableCase for a PhantomReference. * @param cleaner the cleaner to use * @param obj an object or null to create a new Object * @return a new CleanableCase preset with the object, cleanup, and semaphore */ static CleanableCase setupPhantomSubclassException(Cleaner cleaner, Object obj) { if (obj == null) { obj = new Object(); } Semaphore s1 = new Semaphore(0); Cleaner.Cleanable c1 = new PhantomCleanable<Object>(obj, cleaner) { protected void performCleanup() { s1.release(); throw new RuntimeException("Exception thrown to cleaner thread"); } }; return new CleanableCase(new PhantomReference<>(obj, null), c1, s1, true); }
Example #5
Source File: ElasticsearchStore.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
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); }
Example #6
Source File: FinalizableReferenceQueue.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Constructs a new queue. */ public FinalizableReferenceQueue() { // We could start the finalizer lazily, but I'd rather it blow up early. queue = new ReferenceQueue<Object>(); frqRef = new PhantomReference<Object>(this, queue); boolean threadStarted = false; try { startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef); threadStarted = true; } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // startFinalizer() is public } catch (Throwable t) { logger.log( Level.INFO, "Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are created.", t); } this.threadStarted = threadStarted; }
Example #7
Source File: FinalizableReferenceQueue.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Constructs a new queue. */ public FinalizableReferenceQueue() { // We could start the finalizer lazily, but I'd rather it blow up early. queue = new ReferenceQueue<Object>(); frqRef = new PhantomReference<Object>(this, queue); boolean threadStarted = false; try { startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef); threadStarted = true; } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // startFinalizer() is public } catch (Throwable t) { logger.log( Level.INFO, "Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are created.", t); } this.threadStarted = threadStarted; }
Example #8
Source File: TraceCanReliveObj.java From LearningOfThinkInJava with Apache License 2.0 | 6 votes |
@Override public void run() { while (true){ if(phantomQueue!=null){ PhantomReference<TraceCanReliveObj> objt=null; try { objt=(PhantomReference<TraceCanReliveObj>)phantomQueue.remove(); }catch (InterruptedException e){ e.fillInStackTrace(); } if(objt!=null){ System.out.println("TraceCanReliveObj is delete"); } } } }
Example #9
Source File: HashtableCreator.java From openjdk-systemtest with Apache License 2.0 | 6 votes |
private Map<Object,Object> getWeakHashMap(Map<Object,Object> backingMap) { /* * Construct a weak hash map by copying the backingMap * The backing map must be kept alive as long as the returned map is * in scope, otherwise the contents will all end up garbage collected. * Track the WeakhashMap using a PhantomReference queue, so that the * backingmaps can be freed when the WeakHashMap has been GC. */ WeakHashMap<Object,Object> rv = new WeakHashMap<Object,Object>(backingMap); PhantomReference<WeakHashMap<Object,Object>> ref = new PhantomReference<WeakHashMap<Object,Object>>(rv, backingMapQueue); synchronized(backingMaps){ backingMaps.put(ref, backingMap); } return rv; }
Example #10
Source File: FinalizableReferenceQueue.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Constructs a new queue. */ public FinalizableReferenceQueue() { // We could start the finalizer lazily, but I'd rather it blow up early. queue = new ReferenceQueue<Object>(); frqRef = new PhantomReference<Object>(this, queue); boolean threadStarted = false; try { startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef); threadStarted = true; } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // startFinalizer() is public } catch (Throwable t) { logger.log( Level.INFO, "Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are created.", t); } this.threadStarted = threadStarted; }
Example #11
Source File: TraceCanReliveObj.java From LearningOfThinkInJava with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException{ Thread t=new CheckRefQueue(); t.setDaemon(true); t.start(); phantomQueue=new ReferenceQueue<TraceCanReliveObj>(); obj=new TraceCanReliveObj(); PhantomReference<TraceCanReliveObj> phantomRef=new PhantomReference<TraceCanReliveObj>(obj,phantomQueue); obj=null; System.gc(); Thread.sleep(1000); if(obj==null){ System.out.println("obj 是null"); }else { System.out.println("obj 可用"); } System.out.println("第二次gc"); obj=null; System.gc(); Thread.sleep(1000); if(obj==null){ System.out.println("obj是null"); }else { System.out.println("obj 可用"); } }
Example #12
Source File: TraceCanReliveObj.java From LearningOfThinkInJava with Apache License 2.0 | 6 votes |
@Override public void run() { while (true){ if(phantomQueue!=null){ PhantomReference<TraceCanReliveObj> objt=null; try { objt=(PhantomReference<TraceCanReliveObj>)phantomQueue.remove(); }catch (InterruptedException e){ e.fillInStackTrace(); } if(objt!=null){ System.out.println("TraceCanReliveObj is delete"); } } } }
Example #13
Source File: FinalizableReferenceQueue.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Constructs a new queue. */ public FinalizableReferenceQueue() { // We could start the finalizer lazily, but I'd rather it blow up early. queue = new ReferenceQueue<Object>(); frqRef = new PhantomReference<Object>(this, queue); boolean threadStarted = false; try { startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef); threadStarted = true; } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // startFinalizer() is public } catch (Throwable t) { logger.log( Level.INFO, "Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are created.", t); } this.threadStarted = threadStarted; }
Example #14
Source File: PhantomReferenceLimitedPageSource.java From offheap-store with Apache License 2.0 | 6 votes |
/** * Allocates a byte buffer of the given size. * <p> * This {@code BufferSource} places no restrictions on the requested size of * the buffer. */ @Override public Page allocate(int size, boolean thief, boolean victim, OffHeapStorageArea owner) { while (true) { processQueue(); long now = max.get(); if (now < size) { return null; } else if (max.compareAndSet(now, now - size)) { ByteBuffer buffer; try { buffer = ByteBuffer.allocateDirect(size); } catch (OutOfMemoryError e) { return null; } bufferSizes.put(new PhantomReference<>(buffer, allocatedBuffers), size); return new Page(buffer, owner); } } }
Example #15
Source File: SoftCacheTest.java From AVM with MIT License | 6 votes |
/** * This tests fills the cache with 64 KiB byte[] until it observes that the first one has been collected (via PhantomReference). * It then verifies that this entry is also missing from the cache. */ @Test public void testFillUntilClear() throws Exception { SoftCache<String, byte[]> cache = new SoftCache<>(); byte[] element1 = new byte[64 * 1024]; String key1 = "element1"; ReferenceQueue<byte[]> queue = new ReferenceQueue<>(); PhantomReference<byte[]> watcher = new PhantomReference<>(element1, queue); cache.checkin(key1, element1); Assert.assertEquals(element1, cache.checkout(key1)); Assert.assertNull(cache.checkout(key1)); cache.checkin(key1, element1); int i = 0; while (watcher != queue.poll()) { String key = "key_" + i; byte[] value = new byte[64 * 1024]; cache.checkin(key, value); i += 1; } Assert.assertNull(cache.checkout(key1)); }
Example #16
Source File: FinalizableReferenceQueue.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Constructs a new queue. */ public FinalizableReferenceQueue() { // We could start the finalizer lazily, but I'd rather it blow up early. queue = new ReferenceQueue<Object>(); frqRef = new PhantomReference<Object>(this, queue); boolean threadStarted = false; try { startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef); threadStarted = true; } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // startFinalizer() is public } catch (Throwable t) { logger.log( Level.INFO, "Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are created.", t); } this.threadStarted = threadStarted; }
Example #17
Source File: TraceCanReliveObj.java From LearningOfThinkInJava with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException{ Thread t=new CheckRefQueue(); t.setDaemon(true); t.start(); phantomQueue=new ReferenceQueue<TraceCanReliveObj>(); obj=new TraceCanReliveObj(); PhantomReference<TraceCanReliveObj> phantomRef=new PhantomReference<TraceCanReliveObj>(obj,phantomQueue); obj=null; System.gc(); Thread.sleep(1000); if(obj==null){ System.out.println("obj 是null"); }else { System.out.println("obj 可用"); } System.out.println("第二次gc"); obj=null; System.gc(); Thread.sleep(1000); if(obj==null){ System.out.println("obj是null"); }else { System.out.println("obj 可用"); } }
Example #18
Source File: PhantomReferenceCleaner.java From Project with Apache License 2.0 | 6 votes |
public static void main(String[] args) { String abc = new String("123"); ReferenceQueue<String> referenceQueue = new ReferenceQueue<String>(); PhantomReference<String> ref = new PhantomReference<String>(abc, referenceQueue); abc = null; System.gc(); //最好用Debug来调试 Object obj = referenceQueue.poll(); if (obj != null) { Field rereferentVal = null; try { rereferentVal = Reference.class .getDeclaredField("referent"); rereferentVal.setAccessible(true); System.out.println("Before GC Clear:" + rereferentVal.get(obj).toString()); } catch (Exception e) { e.printStackTrace(); } } }
Example #19
Source File: FinalizableReferenceQueue.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Looks up Finalizer.startFinalizer(). */ static Method getStartFinalizer(Class<?> finalizer) { try { return finalizer.getMethod("startFinalizer", Class.class, ReferenceQueue.class, PhantomReference.class); } catch (NoSuchMethodException e) { throw new AssertionError(e); } }
Example #20
Source File: Finalizer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * 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(); }
Example #21
Source File: Finalizer.java From reflectutils with Apache License 2.0 | 5 votes |
/** Constructs a new finalizer thread. */ private Finalizer(Class<?> finalizableReferenceClass, Object frq) { super(Finalizer.class.getName()); this.finalizableReferenceClassReference = new WeakReference<Class<?>>(finalizableReferenceClass); // Keep track of the FRQ that started us so we know when to stop. this.frqReference = new PhantomReference<Object>(frq, queue); setDaemon(true); // TODO: Priority? }
Example #22
Source File: WeakHashMapPlay.java From training with MIT License | 5 votes |
public static void main(String[] args) { String key1 = new String("a1"); // GC Root = Stack Frame (local meth variable) weakMap.put(key1, "v1"); String v2 = "v2"; weakMap.put(new String("a2"), v2); MyDomain v3 = new MyDomain("a3"); weakMapObj.put(v3.id, v3); MyDomain v4 = new MyDomain("a4"); weakMapObj.put(new String("a4"), v4); // daca puneam direct "a4" refolosea instanta din Strng Pool weakValuesMap.put("a5", new WeakReference<MyDomain>(new MyDomain("a5"))); PhantomReference<MyDomain> x; System.gc(); System.out.println(weakMap.get(new String("a1"))); System.out.println(weakMap.get(new String("a2"))); System.out.println(weakMap.size()); System.out.println(weakMapObj.get(new String("a3"))); System.out.println(weakMapObj.get(new String("a4"))); System.out.println(weakValuesMap.get("a5").get()); System.out.println(weakValuesMap.size()); }
Example #23
Source File: Finalizer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** Constructs a new finalizer thread. */ private Finalizer( Class<?> finalizableReferenceClass, ReferenceQueue<Object> queue, PhantomReference<Object> frqReference) { this.queue = queue; this.finalizableReferenceClassReference = new WeakReference<Class<?>>(finalizableReferenceClass); // Keep track of the FRQ that started us so we know when to stop. this.frqReference = frqReference; }
Example #24
Source File: Finalizer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * 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(); }
Example #25
Source File: Finalizer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * 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(); }
Example #26
Source File: ClassForNameLeak.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public static PhantomReference<ClassLoader> loadAndRun(Path jarFilePath) throws Exception { ClassLoader classLoader = new URLClassLoader( new URL[]{jarFilePath.toUri().toURL()}) { @Override public String toString() { return "LeakedClassLoader"; } }; Class<?> loadClass = Class.forName("ClassForName", true, classLoader); ((Runnable) loadClass.newInstance()).run(); PhantomReference<ClassLoader> ref = new PhantomReference<>(classLoader, rq); System.out.println("returning phantom ref: " + ref + " to " + classLoader); return ref; }
Example #27
Source File: Finalizer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** Constructs a new finalizer thread. */ private Finalizer( Class<?> finalizableReferenceClass, ReferenceQueue<Object> queue, PhantomReference<Object> frqReference) { this.queue = queue; this.finalizableReferenceClassReference = new WeakReference<Class<?>>(finalizableReferenceClass); // Keep track of the FRQ that started us so we know when to stop. this.frqReference = frqReference; }
Example #28
Source File: Finalizer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** Constructs a new finalizer thread. */ private Finalizer( Class<?> finalizableReferenceClass, ReferenceQueue<Object> queue, PhantomReference<Object> frqReference) { this.queue = queue; this.finalizableReferenceClassReference = new WeakReference<Class<?>>(finalizableReferenceClass); // Keep track of the FRQ that started us so we know when to stop. this.frqReference = frqReference; }
Example #29
Source File: FinalizableReferenceQueue.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * Looks up Finalizer.startFinalizer(). */ static Method getStartFinalizer(Class<?> finalizer) { try { return finalizer.getMethod("startFinalizer", Class.class, ReferenceQueue.class, PhantomReference.class); } catch (NoSuchMethodException e) { throw new AssertionError(e); } }
Example #30
Source File: Finalizer.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
/** * 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(); }