Search in sources :

Example 26 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));
    Class<?> other_mock_type = cachingMockBytecodeGenerator.mockClass(withMockFeatures(classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.NONE));
    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 27 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));
    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)

Example 28 with ReferenceQueue

use of java.lang.ref.ReferenceQueue in project intellij-community by JetBrains.

the class GCUtil method tryGcSoftlyReachableObjects.

/**
   * Try to force VM to collect soft references if possible.
   * Method doesn't guarantee to succeed, and should not be used in the production code.
   * Commits / hours optimized method code: 5 / 3
   */
@TestOnly
public static void tryGcSoftlyReachableObjects() {
    //long started = System.nanoTime();
    ReferenceQueue<Object> q = new ReferenceQueue<Object>();
    SoftReference<Object> ref = new SoftReference<Object>(new Object(), q);
    ArrayList<SoftReference<?>> list = ContainerUtil.newArrayListWithCapacity(100 + useReference(ref));
    System.gc();
    final long freeMemory = Runtime.getRuntime().freeMemory();
    for (int i = 0; i < 100; i++) {
        if (q.poll() != null) {
            break;
        }
        // full gc is caused by allocation of large enough array below, SoftReference will be cleared after two full gc
        int bytes = Math.min((int) (freeMemory * 0.45), Integer.MAX_VALUE / 2);
        list.add(new SoftReference<Object>(new byte[bytes]));
    }
    // use ref is important as to loop to finish with several iterations: long runs of the method (~80 run of PsiModificationTrackerTest)
    // discovered 'ref' being collected and loop iterated 100 times taking a lot of time
    list.ensureCapacity(list.size() + useReference(ref));
    // do not leave a chance for our created SoftReference's content to lie around until next full GC's
    for (SoftReference createdReference : list) createdReference.clear();
//System.out.println("Done gc'ing refs:" + ((System.nanoTime() - started) / 1000000));
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) SoftReference(java.lang.ref.SoftReference) TestOnly(org.jetbrains.annotations.TestOnly)

Example 29 with ReferenceQueue

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

the class SubclassGC method main.

public static final void main(String[] args) throws Exception {
    System.err.println("\n Regression test for bug 6232010\n");
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManager());
    }
    ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
    ClassLoader loader = new URLClassLoader(((URLClassLoader) systemLoader).getURLs(), systemLoader.getParent());
    Class<? extends ObjectOutputStream> cl = Class.forName(SubclassOfOOS.class.getName(), false, loader).asSubclass(ObjectOutputStream.class);
    Constructor<? extends ObjectOutputStream> cons = cl.getConstructor(OutputStream.class);
    OutputStream os = new ByteArrayOutputStream();
    ObjectOutputStream obj = cons.newInstance(os);
    final ReferenceQueue<Class<?>> queue = new ReferenceQueue<Class<?>>();
    WeakReference<Class<?>> ref = new WeakReference<Class<?>>(cl, queue);
    cl = null;
    obj = null;
    loader = null;
    cons = null;
    systemLoader = null;
    System.err.println("\nStart Garbage Collection right now");
    System.gc();
    Reference<? extends Class<?>> dequeued = queue.remove(TIMEOUT);
    if (dequeued == ref) {
        System.err.println("\nTEST PASSED");
    } else {
        throw new Error();
    }
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) URLClassLoader(java.net.URLClassLoader) WeakReference(java.lang.ref.WeakReference) URLClassLoader(java.net.URLClassLoader)

Example 30 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)

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