简体   繁体   English

双向关系的垃圾收集

[英]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 :我创建了一个新Task并将其存储到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中删除tasks列表:

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)?这些tasks是否会被垃圾收集,或者我是否还需要从所有tasks中显式删除用户实例(为了成功进行垃圾收集)?

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

To be fair, you do not need to do any of those, gc wise.公平地说,你不需要做任何这些, gc明智的。 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). openjdk中没有垃圾收集器基于reference counting算法工作(据我所知,这可能是一个问题)。 While you could both call clear and call set(null) , this will not matter much.虽然您既可以调用clear可以调用set(null) ,但这并不重要。 Unreachable instances will still be collected.仍将收集无法访问的实例。

Garbage collector should free the memory for objects which is no longer reachable.垃圾收集器应为不再可访问的对象释放 memory。 When you are calling the clear method, task objects will no longer have a reference, so they should be eligible for garbage collection even though the object user from inside it is still reachable.当您调用 clear 方法时,任务对象将不再具有引用,因此即使仍然可以访问其中的 object 用户,它们也应该有资格进行垃圾回收。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM