ducin
ducin

Reputation: 26437

java garbage collection issue

I've got a HashMap of Game objects. Each Game object contains a HashMap of Players and a list of Moves. When a game is over, I want to remove it from the map. Shall I empty players map and moves list before I remove the game object or will the GC take care of it?

Yep, that's a newbie question, sorry for that ;)

Upvotes: 2

Views: 110

Answers (2)

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

If you are referring Players HashMap from Game object and when your game is over, and you are removing it from the map, players map will also be removed because it was referenced from game.

When the reference to game is lost then, all the objects which were referred from Game will also be lost if they are not reference from outside Game object

Well let us understand this using an example.

  • We have a Door class and a Room class
  • A Room will have a Door and it cannot exist without the room.

Let us see this code

public class Room {
Door door = new Door();
    public static void main(String[] args) {
        Room room = new Room();
        room = null;
    }

}

Here, When we write Room room = new Room(), a Room object will be created, and because a Door is the instance variable for it, a door is also created. The door will be reference from room using room.door. At this point of time, we can access room directly and its door can be accessed using room. So door object will have reference through room.

Now when we do room = null, we lose the reference to Room object. As the Door object is referenced only through Room, we have lost its only reference. As room = null we can't access room.door.

This is diagrammatically referred as follows

enter image description here

The first image shows the condition when Room room = new Room(); gets executed. It has reference to Door.

The second image denotes the condition after room = null.Please note that dotted line refers that the reference is lost. Now the reference for Room is lost and obviously for the door is also lost.

at this point of time...both objects will be eligible for garbage collection

Hope this answer helps a little bit :)

Upvotes: 3

SLaks
SLaks

Reputation: 887285

You don't need to do anything.

As long as the entire object graph is not referenced by any rooted objects, the GC will collect the whole thing automatically.

A rooted object is an object the is guaranteed to not be collectible – an object referenced by a static field or by an active stack frame in any thread.

Upvotes: 10

Related Questions