Enter your keyword

post

Garbage collection

Definition


Garbage collection is an automatic memory management feature in many modern programming languages, such as Java and languages in the .NET framework. Languages that use garbage collection are often interpreted or run within a virtual machine like the JVM. In each case, the environment that runs the code is also responsible for garbage collection.

Example

public class Test
{

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

Commonly asked interview questions on Constructors

1.What is Garbage Collection in Java?

Answer :Garbage Collection is an automatic memory management feature.
The process of destroying unreferenced objects is called Garbage Collection.
Once object is unreferenced it is considered as unused object, hence JVM automatically destroys that object.
In java developers responsibility is only to creating objects and unreferencing those objects after usage.

2.How JVM can destroy unreferenced object?

Answer :JVM internally uses a daemon thread called “garbage collector” to destroy all unreferenced objects.
A daemon thread is a service thread. Garbage Collector thread is called daemon thread because it provides services to JVM to destroy unreferenced objects.
This thread is low priority thread. Since it is a low priority thread we can not guarantee this execution.

3.What is responsibility of Garbage Collector?

Answer : Garbage Collector frees the memory occupied by the unreachable objects during the java program by deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that there will be sufficient memory for the program to run.

4.When does an object become eligible for garbage collection?

Answer :An object becomes eligible for garbage collection when no live thread can access it.

5.What are the different ways to call garbage collector?

Answer :System.gc();
Runtime.getRuntime().gc();

Take Sample Test

Reference Books


1. Head First Java

No Comments

Add your review

Your email address will not be published.