Search code examples
javagarbage-collection

garbage collection of bidirectional relationships


I have something like this:

The User:

public User {

    List<Task> tasks = new HashSet<>();
    // getter/setter

}

And its tasks:

public Task{

    private User user;
    // getter/setter

}

I create a new Task and store it into User:

var user = new User();
var task1 = new Task();
var task2 = new Task()
task1.setUser(user);
task2.setUser(user);
user.getTasks().add(task1);
user.getTasks().add(task2);

Now the question:

If I delete the the tasks-list from user:

user.getTasks().clear();

will the tasks be garbage collected or do I need to remove the user instance explicitly from all the tasks also (for a successfully garbage collection)?

task1.setUser(null);  // needed?
task2.setUser(null);  // needed?
user.getTasks().clear(); // or is this all I need

Solution

  • To be fair, you do not need to do any of those, gc wise. The way garbage collector traverses live instances it already knows what is alive or not, even if you "chain" those into a recursion. No garbage collector in openjdk works based on the reference counting algorithm (were this could be a problem as far as I see). While you could both call clear and call set(null), this will not matter much. Unreachable instances will still be collected.