How to force garbage collection in Java?

后端 未结 22 1516
离开以前
离开以前 2020-11-22 00:31

Is it possible to force garbage collection in Java, even if it is tricky to do? I know about System.gc(); and Runtime.gc(); but they only suggest t

22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 01:06

    The following code is taken from the assertGC(...) method. It tries to force the nondeterministic garbage collector to collect.

       List alloc = new ArrayList();
       int size = 100000;
       for (int i = 0; i < 50; i++) {
            if (ref.get() == null) {
                 // Test succeeded! Week referenced object has been cleared by gc.
                 return;
            }
            try {
                 System.gc();
            } catch (OutOfMemoryError error) {
                 // OK
            }
            try {
                 System.runFinalization();
            } catch (OutOfMemoryError error) {
                 // OK
            }
    
            // Approach the jvm maximal allocatable memory threshold
            try {
                 // Allocates memory.
                 alloc.add(new byte[size]);
    
                 // The amount of allocated memory is increased for the next iteration.
                 size = (int)(((double)size) * 1.3);
            } catch (OutOfMemoryError error) {
                 // The amount of allocated memory is decreased for the next iteration.
                 size = size / 2;
            }
    
            try {
                 if (i % 3 == 0) Thread.sleep(321);
            } catch (InterruptedException t) {
                 // ignore
            }
       }
    
       // Test failed! 
    
       // Free resources required for testing
       alloc = null;
    
       // Try to find out who holds the reference.
       String str = null;
       try {
            str = findRefsFromRoot(ref.get(), rootsHint);
       } catch (Exception e) {
            throw new AssertionFailedErrorException(e);
       } catch (OutOfMemoryError err) {
            // OK
       }
       fail(text + ":\n" + str);
    

    Source (I added some comments for clarity): NbTestCase Example

提交回复
热议问题