Search in sources :

Example 36 with ReferenceQueue

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

the class TypeCachingMockBytecodeGeneratorTest method ensure_cache_returns_same_instance.

@Test
public void ensure_cache_returns_same_instance() 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));
    Class<?> other_mock_type = cachingMockBytecodeGenerator.mockClass(withMockFeatures(classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.NONE, false, Answers.RETURNS_DEFAULTS));
    assertThat(other_mock_type).isSameAs(the_mock_type);
    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();
    other_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)

Example 37 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project Smack by igniterealtime.

the class MemoryLeakTestUtil method noResourceLeakTest.

@SuppressWarnings("UnusedVariable")
public static <M extends Manager> void noResourceLeakTest(Function<DummyConnection, M> managerSupplier) throws XmppStringprepException, IllegalArgumentException, InterruptedException {
    final int numConnections = 10;
    ReferenceQueue<DummyConnection> connectionsReferenceQueue = new ReferenceQueue<>();
    ReferenceQueue<Manager> managerReferenceQueue = new ReferenceQueue<>();
    // Those two sets ensure that we hold a strong reference to the created PhantomReferences until the end of the
    // test.
    @SuppressWarnings("ModifiedButNotUsed") Set<PhantomReference<DummyConnection>> connectionsPhantomReferences = new HashSet<>();
    @SuppressWarnings("ModifiedButNotUsed") Set<PhantomReference<Manager>> managersPhantomReferences = new HashSet<>();
    List<DummyConnection> connections = new ArrayList<>(numConnections);
    for (int i = 0; i < numConnections; i++) {
        DummyConnection connection = new DummyConnection("foo" + i, "bar", "baz");
        PhantomReference<DummyConnection> connectionPhantomReference = new PhantomReference<>(connection, connectionsReferenceQueue);
        connectionsPhantomReferences.add(connectionPhantomReference);
        Manager manager = managerSupplier.apply(connection);
        PhantomReference<Manager> managerPhantomReference = new PhantomReference<Manager>(manager, managerReferenceQueue);
        managersPhantomReferences.add(managerPhantomReference);
        connections.add(connection);
    }
    // Clear the only references to the created connections.
    connections = null;
    triggerGarbageCollection();
    // Now the connections should have been gc'ed, but not managers not yet.
    assertReferencesQueueSize(connectionsReferenceQueue, numConnections);
    assertReferencesQueueIsEmpty(managerReferenceQueue);
    // We new create another connection and explicitly a new Manager. This will trigger the cleanup mechanism in the
    // WeakHashMaps used by the Manager's iNSTANCE field. This should clean up all references to the Managers.
    DummyConnection connection = new DummyConnection("last", "bar", "baz");
    @SuppressWarnings("unused") Manager manager = managerSupplier.apply(connection);
    // The previous Managers should now be reclaimable by the garbage collector. First trigger a GC run.
    triggerGarbageCollection();
    // Now the Managers should have been freed and this means we should see their phantom references in the
    // reference queue.
    assertReferencesQueueSize(managerReferenceQueue, numConnections);
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) DummyConnection(org.jivesoftware.smack.DummyConnection) ArrayList(java.util.ArrayList) Manager(org.jivesoftware.smack.Manager) PhantomReference(java.lang.ref.PhantomReference) HashSet(java.util.HashSet)

Example 38 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project openj9 by eclipse.

the class Test_PhantomReference method test_Constructor.

/**
 * @tests java.lang.ref.PhantomReference#PhantomReference(java.lang.Object, java.lang.ref.ReferenceQueue)
 */
@Test
public void test_Constructor() {
    ReferenceQueue rq = new ReferenceQueue();
    bool = Boolean.valueOf(true);
    try {
        PhantomReference pr = new PhantomReference(bool, rq);
        // Allow the finalizer to run to potentially enqueue
        Thread.sleep(1000);
        AssertJUnit.assertTrue("Initialization failed.", !pr.isEnqueued());
    } catch (Exception e) {
        AssertJUnit.assertTrue("Exception during test.", false);
    }
    // need a reference to bool so the jit does not optimize it away
    AssertJUnit.assertTrue("should always pass", bool.booleanValue());
    boolean exception = false;
    try {
        new PhantomReference(bool, null);
    } catch (NullPointerException e) {
        exception = true;
    }
    AssertJUnit.assertTrue("Should not throw NullPointerException", !exception);
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) PhantomReference(java.lang.ref.PhantomReference) Test(org.testng.annotations.Test)

Example 39 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project openj9 by eclipse.

the class Test_Reference method test_enqueue.

/**
 * @tests java.lang.ref.Reference#enqueue()
 */
@Test
public void test_enqueue() {
    ReferenceQueue rq = new ReferenceQueue();
    obj = new Object();
    Reference ref = new SoftReference(obj, rq);
    AssertJUnit.assertTrue("Enqueue failed.", (!ref.isEnqueued()) && ((ref.enqueue()) && (ref.isEnqueued())));
    if (isJava8 || disableClearBeforeEnqueue) {
        AssertJUnit.assertTrue("Not properly enqueued.", rq.poll().get() == obj);
    } else {
        AssertJUnit.assertTrue("Not properly enqueued.", rq.poll().get() == null);
    }
    // This fails.
    AssertJUnit.assertTrue("Should remain enqueued.", !ref.isEnqueued());
    AssertJUnit.assertTrue("Can not enqueue twice.", (!ref.enqueue()) && (rq.poll() == null));
    rq = new ReferenceQueue();
    obj = new Object();
    ref = new WeakReference(obj, rq);
    AssertJUnit.assertTrue("Enqueue failed2.", (!ref.isEnqueued()) && ((ref.enqueue()) && (ref.isEnqueued())));
    if (isJava8 || disableClearBeforeEnqueue) {
        AssertJUnit.assertTrue("Not properly enqueued2.", rq.poll().get() == obj);
    } else {
        AssertJUnit.assertTrue("Not properly enqueued2.", rq.poll().get() == null);
    }
    // This fails.
    AssertJUnit.assertTrue("Should remain enqueued2.", !ref.isEnqueued());
    AssertJUnit.assertTrue("Can not enqueue twice2.", (!ref.enqueue()) && (rq.poll() == null));
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) SoftReference(java.lang.ref.SoftReference) Reference(java.lang.ref.Reference) SoftReference(java.lang.ref.SoftReference) WeakReference(java.lang.ref.WeakReference) WeakReference(java.lang.ref.WeakReference) Test(org.testng.annotations.Test)

Example 40 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project openj9 by eclipse.

the class Test_Reference method test_clear.

/**
 * @tests java.lang.ref.Reference#clear()
 */
@Test
public void test_clear() {
    tmpA = new Object();
    tmpB = new Object();
    SoftReference sr = new SoftReference(tmpA, new ReferenceQueue());
    WeakReference wr = new WeakReference(tmpB, new ReferenceQueue());
    AssertJUnit.assertTrue("Start: Object not cleared.", (sr.get() != null) && (wr.get() != null));
    sr.clear();
    wr.clear();
    AssertJUnit.assertTrue("End: Object cleared.", (sr.get() == null) && (wr.get() == null));
    // Must reference tmpA and tmpB so the jit does not optimize them away
    AssertJUnit.assertTrue("should always pass", tmpA != sr.get() && tmpB != wr.get());
}
Also used : SoftReference(java.lang.ref.SoftReference) ReferenceQueue(java.lang.ref.ReferenceQueue) WeakReference(java.lang.ref.WeakReference) Test(org.testng.annotations.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