Garbage collection in Java

Walden Systems Geeks corner tutorial Garbage collection in Java programming developer how to Rutherford NJ New Jersey NYC New York North Bergen County
Java Powers the Biggest Technology. Mobile. Web apps. The Internet of Things. Big data. Machine learning. Cloud platform and cloud infrastructure. The next big things are here now, and Java is at the center of them all. Whether you’re developing the robust enterprise back end, building the agile front end, or thriving in a DevOps role, Java skills can up your game. With more than 10 million programmers and 13 billion Java-enabled devices worldwide, Java is the language that connects applications to data, data to people, and people to their digital lifestyle.

In Java destruction of object from memory is done automatically by the JVM. When there is no reference to an object, then that object is assumed to be no longer needed and the memory occupied by the object are released. This technique is called Garbage Collection. This is accomplished by the JVM. Unlike C++ there is no explicit need to destroy object. the Garbage Collection can not be forced explicitly. We may request JVM for garbage collection by calling System.gc() method. But This does not guarantee that JVM will perform the garbage collection.

Finalize()

Sometime an object will need to perform some specific task before it is destroyed such as closing an open connection or releasing any resources held. To handle such situation finalize() method is used. finalize() method is called by garbage collection thread before collecting object. Its the last chance for any object to perform cleanup utility. The finalize() method is defined in java.lang.Object class and it is available to all the classes. The method is defined in java.lang.Object class, therefore it is available to all the classes. The method gets called only once by a Daemon thread named GC (Garbage Collector)thread.


Gc()

The gc() method is used to call garbage collector explicitly. Calling the gc() method does not guarantee that JVM will perform the garbage collection. It only request the JVM for garbage collection. This method is present in System and Runtime class.

public class Example
{

    public static void main(String[] args)
    {
        Test t = new Test();
        t=null;
        System.gc();
    }
    public void finalize()
    {
        System.out.println("Cleaned");
    }
}

The main objective of Garbage Collector is to free heap memory by destroying unreachable objects. An object is said to be unreachable if and only if it doesn’t contain any reference to it. Even though programmer is not responsible to destroy useless objects but it is highly recommended to make an object unreachable if it is no longer required. We can make an object eligible for garbage collection by nulling the reference variable.