Search in sources :

Example 6 with Reference

use of java.lang.ref.Reference in project robovm by robovm.

the class PhantomReferenceTest method test_gcInteraction.

/**
     * java.lang.Runtime#gc()
     */
public void test_gcInteraction() {
    class TestPhantomReference<T> extends PhantomReference<T> {

        public TestPhantomReference(T referent, ReferenceQueue<? super T> q) {
            super(referent, q);
        }

        public boolean enqueue() {
            // Initiate another GC from inside enqueue() to
            // see if it causes any problems inside the VM.
            Runtime.getRuntime().gc();
            return super.enqueue();
        }
    }
    final ReferenceQueue rq = new ReferenceQueue();
    final PhantomReference[] tprs = new PhantomReference[4];
    class TestThread extends Thread {

        public void run() {
            // Create the object in a separate thread to ensure
            // it will be gc'ed.
            Object obj = new Object();
            tprs[0] = new TestPhantomReference(obj, rq);
            tprs[1] = new TestPhantomReference(obj, rq);
            tprs[2] = new TestPhantomReference(obj, rq);
            tprs[3] = new TestPhantomReference(obj, rq);
        }
    }
    try {
        Thread t = new TestThread();
        t.start();
        t.join();
        FinalizationTester.induceFinalization();
        assertNull("get() should return null.", tprs[0].get());
        assertNull("get() should return null.", tprs[1].get());
        assertNull("get() should return null.", tprs[2].get());
        assertNull("get() should return null.", tprs[3].get());
        for (int i = 0; i < 4; i++) {
            Reference r = rq.remove(100L);
            assertNotNull("Reference should have been enqueued.", r);
        }
        // These are to make sure that tprs and its elements don't get
        // optimized out.
        assertNull("get() should return null.", tprs[0].get());
        assertNull("get() should return null.", tprs[1].get());
        assertNull("get() should return null.", tprs[2].get());
        assertNull("get() should return null.", tprs[3].get());
    } catch (InterruptedException e) {
        fail("InterruptedException : " + e.getMessage());
    }
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) PhantomReference(java.lang.ref.PhantomReference) Reference(java.lang.ref.Reference) PhantomReference(java.lang.ref.PhantomReference)

Example 7 with Reference

use of java.lang.ref.Reference in project scriptographer by scriptographer.

the class SoftIntMap method purge.

/**
	 *  Purges stale mappings from this map.<P>
	 *
	 *  Ordinarily, stale mappings are only removed during
	 *  a write operation; typically a write operation will    
	 *  occur often enough that you'll never need to manually
	 *  invoke this method.<P>
	 *
	 *  Note that this method is not synchronized!  Special
	 *  care must be taken if, for instance, you want stale
	 *  mappings to be removed on a periodic basis by some
	 *  background thread.
	 */
protected void purge() {
    Reference ref = queue.poll();
    while (ref != null) {
        ref.clear();
        ref = queue.poll();
    }
}
Also used : Reference(java.lang.ref.Reference) SoftReference(java.lang.ref.SoftReference)

Example 8 with Reference

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

the class RuntimeThreadInheritanceLeak method main.

public static void main(String[] args) {
    System.err.println("\nRegression test for bug 4404702\n");
    /*
         * HACK: Work around the fact that java.util.logging.LogManager's
         * (singleton) construction also has this bug-- it will register a
         * "shutdown hook", i.e. a thread, which will inherit and pin the
         * current thread's context class loader for the lifetime of the VM--
         * by causing the LogManager to be initialized now, instead of by
         * RMI when our special context class loader is set.
         */
    java.util.logging.LogManager.getLogManager();
    /*
         * HACK: Work around the fact that the non-native, thread-based
         * SecureRandom seed generator (ThreadedSeedGenerator) seems to
         * have this bug too (which had been causing this test to fail
         * when run with jtreg on Windows XP-- see 4910382).
         */
    (new java.security.SecureRandom()).nextInt();
    RuntimeThreadInheritanceLeak obj = new RuntimeThreadInheritanceLeak();
    try {
        ClassLoader loader = URLClassLoader.newInstance(new URL[0]);
        ReferenceQueue refQueue = new ReferenceQueue();
        Reference loaderRef = new WeakReference(loader, refQueue);
        System.err.println("created loader: " + loader);
        Thread.currentThread().setContextClassLoader(loader);
        UnicastRemoteObject.exportObject(obj);
        Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
        System.err.println("exported remote object with loader as context class loader");
        loader = null;
        System.err.println("nulled strong reference to loader");
        UnicastRemoteObject.unexportObject(obj, true);
        System.err.println("unexported remote object");
        /*
             * HACK: Work around the fact that the sun.misc.GC daemon thread
             * also has this bug-- it will have inherited our loader as its
             * context class loader-- by giving it a chance to pass away.
             */
        Thread.sleep(2000);
        System.gc();
        System.err.println("waiting to be notified of loader being weakly reachable...");
        Reference dequeued = refQueue.remove(TIMEOUT);
        if (dequeued == null) {
            System.err.println("TEST FAILED: loader not deteced weakly reachable");
            dumpThreads();
            throw new RuntimeException("TEST FAILED: loader not detected weakly reachable");
        }
        System.err.println("TEST PASSED: loader detected weakly reachable");
        dumpThreads();
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException("TEST FAILED: unexpected exception", e);
    } finally {
        try {
            UnicastRemoteObject.unexportObject(obj, true);
        } catch (RemoteException e) {
        }
    }
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) Reference(java.lang.ref.Reference) WeakReference(java.lang.ref.WeakReference) WeakReference(java.lang.ref.WeakReference) URLClassLoader(java.net.URLClassLoader) RemoteException(java.rmi.RemoteException) RemoteException(java.rmi.RemoteException)

Example 9 with Reference

use of java.lang.ref.Reference 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 10 with Reference

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

the class ConstantPoolInfoGC method runTests.

/********** test core **********/
protected void runTests() throws Exception {
    targetClass = startToMain("ConstantPoolGCTarg").location().declaringType();
    if (vm().canGetConstantPool()) {
        byte[] cpbytes = targetClass.constantPool();
        // imitate SoftReference cleared
        Field constantPoolBytesRef = ReferenceTypeImpl.class.getDeclaredField("constantPoolBytesRef");
        constantPoolBytesRef.setAccessible(true);
        Reference softRef = (Reference) constantPoolBytesRef.get(targetClass);
        softRef.clear();
        byte[] cpbytes2 = targetClass.constantPool();
        if (!Arrays.equals(cpbytes, cpbytes2)) {
            failure("Consequent constantPool results vary, first was : " + cpbytes + ", now: " + cpbytes2);
        }
        ;
    } else {
        System.out.println("can get constant pool version not supported");
    }
    /*
         * resume until end
         */
    listenUntilVMDisconnect();
    /*
         * deal with results of test
         * if anything has called failure("foo") testFailed will be true
         */
    if (!testFailed) {
        println("ConstantPoolInfoGC: passed");
    } else {
        throw new Exception("ConstantPoolInfoGC: failed");
    }
}
Also used : Field(java.lang.reflect.Field) Reference(java.lang.ref.Reference)

Aggregations

Reference (java.lang.ref.Reference)31 WeakReference (java.lang.ref.WeakReference)17 PhantomReference (java.lang.ref.PhantomReference)10 ReferenceQueue (java.lang.ref.ReferenceQueue)10 SoftReference (java.lang.ref.SoftReference)10 Field (java.lang.reflect.Field)5 Map (java.util.Map)5 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 ConcurrentMap (java.util.concurrent.ConcurrentMap)3 IOException (java.io.IOException)2 AccessControlContext (java.security.AccessControlContext)2 HashSet (java.util.HashSet)2 Iterator (java.util.Iterator)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Supplier (com.google.common.base.Supplier)1 SoftReference (com.intellij.reference.SoftReference)1 SideEffect (dalvik.annotation.SideEffect)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1