KodeSaga
KodeSaga

Reputation: 39

Object reference variable reassignment

What happens to the object if I reassign its reference variable to another object? How does Java manage this object which does not have any reference variable now?

Objects exist on Heap of the memory, I tried but could not find how Java manages such "dangling" objects as described below.

class Box{...}
...
Box b1 = new Box(); //Instance 1
Box b2 = new Box(); //Instance 2
b1 = b2;
....

Here as you can see Instance 1 has lost its reference variable. What happens to this object? How Java/JVM manages such scenarios if in case it occurs?

Upvotes: 0

Views: 391

Answers (3)

E.Omar
E.Omar

Reputation: 119

Garbage Collector will clean the memory space which is taken by the object when it is no longer reachable . Reachable simply means that there is no such reference to this object. In the example you provide the object referenced by b2 will be garbage collected since there is no such reference to be used to access the object, but if there is any other reference to that object won't be garbage collected as the following example

Box b1 = new Box(); //Instance 1
Box b2 = new Box(); //Instance 2
Box b3 = b2;
b1 = null;
b2 = null;

now the object referenced by b1 will be garbage collected, but the object referenced by b2 won't. Because b3 is referencing the object was referenced by b2.

Upvotes: 1

templatetypedef
templatetypedef

Reputation: 372814

Java uses garbage collection to automatically detect and reclaim memory for objects that are no longer referenced. The actual mechanism used depends on which Java implementation you're using. Most JVMs use a combination of different techniques, typically using a stop-and-copy collector for new objects along with a mark-and-sweep collector for longer-lived objects. This is a super interesting area to dive deeper into if you're curious to see how it works!

Upvotes: 1

Ortomala Lokni
Ortomala Lokni

Reputation: 62515

The object that was referenced by b1 will be garbage collected:

Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

Upvotes: 3

Related Questions