How to force garbage collection in Java?

后端 未结 22 1522
离开以前
离开以前 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条回答
  • 2020-11-22 00:57

    FYI

    The method call System.runFinalizersOnExit(true) guarantees that finalizer methods are called before Java shuts down. However, this method is inherently unsafe and has been deprecated. An alternative is to add “shutdown hooks” with the method Runtime.addShutdownHook.

    Masarrat Siddiqui

    0 讨论(0)
  • 2020-11-22 01:01

    If you need to force garbage collection, perhaps you should consider how you're managing resources. Are you creating large objects that persist in memory? Are you creating large objects (e.g., graphics classes) that have a Disposable interface and not calling dispose() when done with it? Are you declaring something at a class level that you only need within a single method?

    0 讨论(0)
  • 2020-11-22 01:02

    You can try using Runtime.getRuntime().gc() or use utility method System.gc() Note: These methods do not ensure GC. And their scope should be limited to JVM rather than programmatically handling it in your application.

    0 讨论(0)
  • 2020-11-22 01:06

    YES it is almost possible to forced you have to call to methods in the same order and at the same time this ones are:

    System.gc ();
    System.runFinalization ();
    

    even if is just one object to clean the use of this two methods at the same time force the garbage collector to use the finalise() method of unreachable object freeing the memory assigned and doing what the finalize() method states.

    HOWEVER it is a terrible practice to use the garbage collector because the use of it could introduce an over load to the software that may be even worst than on the memory, the garbage collector has his own thread which is not possible to control plus depending on the algorithm used by the gc could take more time and is consider very inefficient, you should check your software if it worst with the help of the gc because it is definitely broke, a good solution must not depend on the gc.

    NOTE: just to keep on mind this will works only if in the finalize method is not a reassignment of the object, if this happens the object will keep alive an it will have a resurrection which is technically possible.

    0 讨论(0)
  • 2020-11-22 01:06

    .gc is a candidate for elimination in future releases - a Sun Engineer once commented that maybe fewer than twenty people in the world actually know how to use .gc() - I did some work last night for a few hours on a central / critical data-structure using SecureRandom generated data, at somewhere just past 40,000 objects the vm would slow down as though it had run out of pointers. Clearly it was choking down on 16-bit pointer tables and exhibited classic "failing machinery" behavior.

    I tried -Xms and so on, kept bit twiddling until it would run to about 57,xxx something. Then it would run gc going from say 57,127 to 57,128 after a gc() - at about the pace of code-bloat at camp Easy Money.

    Your design needs fundamental re-work, probably a sliding window approach.

    0 讨论(0)
  • 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<byte[]> alloc = new ArrayList<byte[]>();
       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

    0 讨论(0)
提交回复
热议问题