Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Tell If an Object Has Been Garbage Collected

How I can know to tell if an Object has been garbage collected or not?

like image 480
user2110292 Avatar asked Mar 17 '13 11:03

user2110292


People also ask

How can you make sure an object is garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it.

Can an object be garbage collected while it is still reachable?

It's possible to have unused objects that are still reachable by an application because the developer simply forgot to dereference them. Such objects cannot be garbage-collected.

Can you explain garbage collection with an example?

Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program.

Which method is called just before an object is garbage collected?

It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.


1 Answers

According to this:

You normally can’t tell whether an object has been garbage collected by using some reference to the object–because once you have a reference to the object, it won’t be garbage collected.

You can instead create a weak reference to an object using the WeakReference object. The weak reference is one that won’t be counted as a reference, for purposes of garbage collection.

In the code below, we check before and after garbage collection to show that a Dog object is garbage collected.

Dog dog = new Dog("Bowser");

WeakReference dogRef = new WeakReference(dog);
Console.WriteLine(dogRef.IsAlive);

dog = null;
GC.Collect();

Console.WriteLine(dogRef.IsAlive);

enter image description here

like image 91
user2110292 Avatar answered Oct 13 '22 01:10

user2110292