Ways to create an object for explicit garbage collection

I read about making an object explicitly garbage collected, which is a lot. So I wanted to know some of the ways to make this explicitly garbage collected.

+4
source share
4 answers

System.gc means that the JVM explicitly runs the garbage collector.

But, since some methods that I know to make an object explicitly garbage collected are as follows:

Assigning a reference to null EX: Animal a = new Animal (); a = null

Assign a link to link to another object. EX: Animal a1 = new Animal (); a1 = new Animal ();

+1
source

There is no way to explicitly collect garbage.

You can politely ask the virtual machine to collect garbage by calling:

System.gc(); 

but it is not guaranteed.

Calling the gc method assumes that the Java virtual machine spends the effort of reusing unused objects to make the memory they currently occupy for quick reuse. When control returns from the method call, the Java virtual machine has made every effort to free up space from all dropped objects.

and the “best effort” may be to defer garbage collection.

To make elligible objects for garbage collection, read Effective Java, chapter 2

+6
source

You can explicitly make an object suitable for garbage collection by setting all references to null for it.

This will not cause the garbage collector, but when the build begins, it will collect this object.

It is best to allow the Java garbage collector to do everything automatically by itself. It has been optimized to the point that it will be better and more effective than anything you would ever want to do.

+2
source

You don’t have to worry about forcing the use of GC unless you write, say, a tool like VisualVM yourself.

NetBeans, IntelliJ, VisualVM, and many others can push GC, not hint, but actually force. Using JVMTI, you can force GC.

BUT again you are likely to do NOT to do this.

You press GC (not a hint) using the JVMTI ForceGarbageCollection.

However, you probably really DO NOT want to do this (it really can repeat).

Authoritative information on this subject, if you really want to find out (but probably not) how to force, in essence, GC:

http://java.sun.com/javase/6/docs/platform/jvmti/jvmti.html#ForceGarbageCollection

+1
source

Source: https://habr.com/ru/post/1300329/


All Articles