Garbage Collection in JAVA

There part 2 parts of multi tasking in Computer science.

   1. process based multi tasking.

process:Simply any program run in OS called process,Self contain execution environment.(A private set of basic runtime resources;allocate memory space for each every program in RAM Stack)Thus we can run many program in one now a days OS's which means process based multi tasking.process allocate memory space for the program

    2.Thread based multi Tasking.

Threads:Any  code context has a thread.thread will execute the code.So some of thread can execute 2 or more program concurrency that called Thread based multi Tasking.Also  light weigh process,because It takes less memory space compare to the processes.

Garbage collector

Each & every thread  has a specific stack.So stack is thread safety(Stack store local variables & parameters so they are thread safe),but heap is not(Objects are not thread safe).As well as heap is common.So there is a tendency to overflow the heap.so there is an inbuilt solution in java to avoid this problem called Garbage collector.

Java garbage collection is the process by which Java programs perform automatic memory management.When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program.

garbage collector is a special kind of thread which destroy object which are no longer needed to program.

If it wants to clean the heap ,JVM automatically invoked the grabage collector.If you want to invoke gc forcefully we can use,System.gc();(But not recommend @ every time).

Eg:-

public class AppInizializer {

    public static void main(String[] args) {

        AppInizializer obj = new AppInizializer();

        System.out.println(obj.hashCode());

        obj = null;

        // invoke garbage collector

        System.gc();

        System.out.println("invoke garbage collection");

    }


    @Override

    //This method is invoke just before an object is garbage collected. 

    //Destroy unconnected objects

    protected void finalize() {

        System.out.println("finalize method called");

    }

}

Pictorial Java: Garbage collection with example : The Pictorial Way


Comments

Popular posts from this blog

Hibernate-2

Hibernate-1

Avoid Round-off error in large & Small numbers using BigDecimal Class in Java