Search in sources :

Example 11 with ReferenceQueue

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

the class JpegWriterLeakTest method main.

public static void main(String[] args) {
    final ReferenceQueue<ImageWriter> queue = new ReferenceQueue<>();
    final ArrayList<Reference<? extends ImageWriter>> refs = new ArrayList<>();
    int count = 2;
    do {
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        final WeakReference<? extends ImageWriter> ref = new WeakReference<>(writer, queue);
        refs.add(ref);
        try {
            final ImageOutputStream os = ImageIO.createImageOutputStream(new ByteArrayOutputStream());
            writer.setOutput(os);
            writer.write(getImage());
        // NB: dispose() or reset() workarounds the problem.
        } catch (IOException e) {
        } finally {
            writer = null;
        }
        count--;
    } while (count > 0);
    System.out.println("Wait for GC...");
    final long testTimeOut = 60000L;
    final long startTime = System.currentTimeMillis();
    while (!refs.isEmpty()) {
        // check for the test timeout
        final long now = System.currentTimeMillis();
        if (now - startTime > testTimeOut) {
            System.out.println();
            throw new RuntimeException("Test FAILED.");
        }
        System.gc();
        try {
            System.out.print(".");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        ;
        Reference<? extends ImageWriter> r = queue.poll();
        if (r != null) {
            System.out.println("Got reference: " + r);
            refs.remove(r);
        }
    }
    System.out.println("Test PASSED.");
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) Reference(java.lang.ref.Reference) WeakReference(java.lang.ref.WeakReference) ImageWriter(javax.imageio.ImageWriter) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) WeakReference(java.lang.ref.WeakReference) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 12 with ReferenceQueue

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

the class DGCImplInsulation method main.

public static void main(String[] args) throws Exception {
    TestLibrary.suggestSecurityManager(null);
    Permissions perms = new Permissions();
    perms.add(new SocketPermission("*:1024-", "listen"));
    AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(new CodeSource(null, (Certificate[]) null), perms) });
    Remote impl = new DGCImplInsulation();
    ;
    try {
        Remote stub = (Remote) java.security.AccessController.doPrivileged(new ExportAction(impl));
        System.err.println("exported remote object; local stub: " + stub);
        MarshalledObject mobj = new MarshalledObject(stub);
        stub = (Remote) mobj.get();
        System.err.println("marshalled/unmarshalled stub: " + stub);
        ReferenceQueue refQueue = new ReferenceQueue();
        Reference weakRef = new WeakReference(impl, refQueue);
        impl = null;
        System.gc();
        if (refQueue.remove(TIMEOUT) == weakRef) {
            throw new RuntimeException("TEST FAILED: remote object garbage collected");
        } else {
            System.err.println("TEST PASSED");
            stub = null;
            System.gc();
            Thread.sleep(2000);
            System.gc();
        }
    } finally {
        try {
            UnicastRemoteObject.unexportObject(impl, true);
        } catch (Exception e) {
        }
    }
}
Also used : ProtectionDomain(java.security.ProtectionDomain) ReferenceQueue(java.lang.ref.ReferenceQueue) Reference(java.lang.ref.Reference) WeakReference(java.lang.ref.WeakReference) SocketPermission(java.net.SocketPermission) Remote(java.rmi.Remote) CodeSource(java.security.CodeSource) AccessControlContext(java.security.AccessControlContext) MarshalledObject(java.rmi.MarshalledObject) WeakReference(java.lang.ref.WeakReference) Permissions(java.security.Permissions) Certificate(java.security.cert.Certificate)

Example 13 with ReferenceQueue

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

the class SessionGarbageCollectedTest method testSessionsGetGarbageCollected.

public void testSessionsGetGarbageCollected() throws RepositoryException {
    ArrayList<WeakReference<Session>> list = new ArrayList<WeakReference<Session>>();
    ReferenceQueue<Session> detect = new ReferenceQueue<Session>();
    Error error = null;
    try {
        for (int i = 0; ; i++) {
            Session s = getHelper().getReadWriteSession();
            // eat  a lot of memory so it gets garbage collected quickly
            // (or quickly runs out of memory)
            Node n = s.getRootNode().addNode("n" + i);
            n.setProperty("x", new String(new char[1000000]));
            list.add(new WeakReference<Session>(s, detect));
            if (detect.poll() != null) {
                break;
            }
        }
    } catch (OutOfMemoryError e) {
        error = e;
    }
    for (int i = 0; i < list.size(); i++) {
        Reference<Session> ref = list.get(i);
        Session s = ref.get();
        if (s != null) {
            s.logout();
        }
    }
    if (error != null) {
        throw error;
    }
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) Node(javax.jcr.Node) ArrayList(java.util.ArrayList) WeakReference(java.lang.ref.WeakReference) Session(javax.jcr.Session)

Example 14 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 15 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project byte-buddy by raphw.

the class NexusTest method testNexusClean.

@Test
public void testNexusClean() throws Exception {
    Field typeInitializers = ClassLoader.getSystemClassLoader().loadClass(Nexus.class.getName()).getDeclaredField("TYPE_INITIALIZERS");
    typeInitializers.setAccessible(true);
    ClassLoader classLoader = new URLClassLoader(new URL[0]);
    when(loadedTypeInitializer.isAlive()).thenReturn(true);
    assertThat(((Map<?, ?>) typeInitializers.get(null)).isEmpty(), is(true));
    ReferenceQueue<ClassLoader> referenceQueue = new ReferenceQueue<ClassLoader>();
    NexusAccessor nexusAccessor = new NexusAccessor(referenceQueue);
    nexusAccessor.register(FOO, classLoader, BAR, loadedTypeInitializer);
    assertThat(((Map<?, ?>) typeInitializers.get(null)).isEmpty(), is(false));
    classLoader = null;
    System.gc();
    NexusAccessor.clean(referenceQueue.remove(100L));
    assertThat(((Map<?, ?>) typeInitializers.get(null)).isEmpty(), is(true));
}
Also used : Field(java.lang.reflect.Field) ReferenceQueue(java.lang.ref.ReferenceQueue) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) ByteArrayClassLoader(net.bytebuddy.dynamic.loading.ByteArrayClassLoader) Test(org.junit.Test)

Aggregations

ReferenceQueue (java.lang.ref.ReferenceQueue)30 WeakReference (java.lang.ref.WeakReference)15 PhantomReference (java.lang.ref.PhantomReference)11 Reference (java.lang.ref.Reference)10 SoftReference (java.lang.ref.SoftReference)9 URLClassLoader (java.net.URLClassLoader)3 Test (org.junit.Test)3 ArrayList (java.util.ArrayList)2 ClassLoaders.inMemoryClassLoader (org.mockitoutil.ClassLoaders.inMemoryClassLoader)2 SideEffect (dalvik.annotation.SideEffect)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 MarshalledObject (java.rmi.MarshalledObject)1 Remote (java.rmi.Remote)1 RemoteException (java.rmi.RemoteException)1 AccessControlContext (java.security.AccessControlContext)1