Search in sources :

Example 31 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project jdk8u_jdk by JetBrains.

the class ClearStaleZipFileInputStreams method runTest.

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();
    }
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) ZipFile(java.util.zip.ZipFile) InputStream(java.io.InputStream) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 32 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project groovy by apache.

the class Memoize method buildSoftReferenceMemoizeFunction.

/**
     * Creates a new closure delegating to the supplied one and memoizing all return values by the arguments.
     * The memoizing closure will use SoftReferences to remember the return values allowing the garbage collector
     * to reclaim the memory, if needed.
     *
     * The supplied cache is used to store the memoized values and it is the cache's responsibility to put limits
     * on the cache size or implement cache eviction strategy.
     * The LRUCache, for example, allows to set the maximum cache size constraint and implements
     * the LRU (Last Recently Used) eviction strategy.
     *
     * If the protectedCacheSize argument is greater than 0 an optional LRU (Last Recently Used) cache of hard references
     * is maintained to protect recently touched memoized values against eviction by the garbage collector.
     *
     * @param protectedCacheSize The number of hard references to keep in order to prevent some (LRU) memoized return values from eviction
     * @param cache A map to hold memoized return values
     * @param closure The closure to memoize
     * @param <V> The closure's return type
     * @return A new memoized closure
     */
public static <V> Closure<V> buildSoftReferenceMemoizeFunction(final int protectedCacheSize, final MemoizeCache<Object, Object> cache, final Closure<V> closure) {
    final ProtectionStorage lruProtectionStorage = protectedCacheSize > 0 ? new LRUProtectionStorage(protectedCacheSize) : // Nothing should be done when no elements need protection against eviction
    new NullProtectionStorage();
    final ReferenceQueue queue = new ReferenceQueue();
    return new SoftReferenceMemoizeFunction<V>(cache, closure, lruProtectionStorage, queue);
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue)

Example 33 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project grpc-java by grpc.

the class ManagedChannelOrphanWrapperTest method orphanedChannelsAreLogged.

@Test
public void orphanedChannelsAreLogged() {
    ManagedChannel mc = new TestManagedChannel();
    String channelString = mc.toString();
    final ReferenceQueue<ManagedChannelOrphanWrapper> refqueue = new ReferenceQueue<>();
    ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs = new ConcurrentHashMap<>();
    assertEquals(0, refs.size());
    @SuppressWarnings("UnusedVariable") ManagedChannelOrphanWrapper channel = new ManagedChannelOrphanWrapper(mc, refqueue, refs);
    assertEquals(1, refs.size());
    // Try to capture the log output but without causing terminal noise.  Adding the filter must
    // be done before clearing the ref or else it might be missed.
    final List<LogRecord> records = new ArrayList<>(1);
    Logger orphanLogger = Logger.getLogger(ManagedChannelOrphanWrapper.class.getName());
    Filter oldFilter = orphanLogger.getFilter();
    orphanLogger.setFilter(new Filter() {

        @Override
        public boolean isLoggable(LogRecord record) {
            synchronized (records) {
                records.add(record);
            }
            return false;
        }
    });
    try {
        channel = null;
        final AtomicInteger numOrphans = new AtomicInteger();
        GcFinalization.awaitDone(new FinalizationPredicate() {

            @Override
            public boolean isDone() {
                numOrphans.getAndAdd(ManagedChannelReference.cleanQueue(refqueue));
                return numOrphans.get() > 0;
            }
        });
        assertEquals("unexpected extra orphans", 1, numOrphans.get());
        LogRecord lr;
        synchronized (records) {
            assertEquals(1, records.size());
            lr = records.get(0);
        }
        assertThat(lr.getMessage()).contains("shutdown");
        assertThat(lr.getParameters()).asList().containsExactly(channelString).inOrder();
        assertEquals(Level.SEVERE, lr.getLevel());
        assertEquals(0, refs.size());
    } finally {
        orphanLogger.setFilter(oldFilter);
    }
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) ArrayList(java.util.ArrayList) Logger(java.util.logging.Logger) ManagedChannelReference(io.grpc.internal.ManagedChannelOrphanWrapper.ManagedChannelReference) LogRecord(java.util.logging.LogRecord) Filter(java.util.logging.Filter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ManagedChannel(io.grpc.ManagedChannel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) FinalizationPredicate(com.google.common.testing.GcFinalization.FinalizationPredicate) Test(org.junit.Test)

Example 34 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project roboguice by roboguice.

the class WeakKeySetUtils method awaitFullGc.

public static void awaitFullGc() {
    // GcFinalization *should* do it, but doesn't work well in practice...
    // so we put a second latch and wait for a ReferenceQueue to tell us.
    ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
    WeakReference ref = new WeakReference<Object>(new Object(), queue);
    GcFinalization.awaitFullGc();
    try {
        assertSame("queue didn't return ref in time", ref, queue.remove(5000));
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) WeakReference(java.lang.ref.WeakReference)

Example 35 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project mockito by mockito.

the class TypeCachingMockBytecodeGeneratorTest method ensure_cache_is_cleared_if_no_reference_to_classloader_and_classes.

@Test
public void ensure_cache_is_cleared_if_no_reference_to_classloader_and_classes() throws Exception {
    // given
    ClassLoader classloader_with_life_shorter_than_cache = inMemoryClassLoader().withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar")).build();
    TypeCachingBytecodeGenerator cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true);
    Class<?> the_mock_type = cachingMockBytecodeGenerator.mockClass(withMockFeatures(classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.NONE, false, Answers.RETURNS_DEFAULTS));
    ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
    Reference<Object> typeReference = new PhantomReference<Object>(the_mock_type, referenceQueue);
    // when
    classloader_with_life_shorter_than_cache = is_no_more_referenced();
    the_mock_type = is_no_more_referenced();
    System.gc();
    ensure_gc_happened();
    // then
    assertThat(referenceQueue.poll()).isEqualTo(typeReference);
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) PhantomReference(java.lang.ref.PhantomReference) ClassLoaders.inMemoryClassLoader(org.mockitoutil.ClassLoaders.inMemoryClassLoader) Test(org.junit.Test)

Aggregations

ReferenceQueue (java.lang.ref.ReferenceQueue)41 WeakReference (java.lang.ref.WeakReference)20 PhantomReference (java.lang.ref.PhantomReference)14 SoftReference (java.lang.ref.SoftReference)14 Reference (java.lang.ref.Reference)13 Test (org.testng.annotations.Test)8 ArrayList (java.util.ArrayList)4 Test (org.junit.Test)4 URLClassLoader (java.net.URLClassLoader)3 ClassLoaders.inMemoryClassLoader (org.mockitoutil.ClassLoaders.inMemoryClassLoader)2 FinalizationPredicate (com.google.common.testing.GcFinalization.FinalizationPredicate)1 SideEffect (dalvik.annotation.SideEffect)1 ManagedChannel (io.grpc.ManagedChannel)1 ManagedChannelReference (io.grpc.internal.ManagedChannelOrphanWrapper.ManagedChannelReference)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Field (java.lang.reflect.Field)1 SocketPermission (java.net.SocketPermission)1