简体   繁体   English

从地图中删除Java垃圾收集实例?

[英]Java Garbage Collecting instance upon removal from map?

I've been trying to be more and more memory focused, and have a question about garbage collecting. 我一直在尝试越来越关注内存,并对垃圾回收有疑问。

In this case Profile would be a class we have in our program, but the profile would only be necessary when the user is actually logged in. 在这种情况下,Profile是我们程序中的一个类,但是只有在用户实际登录时才需要Profile。

Map<UUID, Profile> profiles;

public ProfileManager() {
    profiles = new HashMap<UUID, Profile>();
}

public void login(UUID uuid) {
    profiles.put(uuid, new Profile(uuid));
}

public void logout(UUID uuid) {
    if(profiles.containsKey(uuid))
        profiles.remove(uuid);
}

My question is, would it garbage collect the removed profile? 我的问题是,是否会垃圾收集已删除的个人资料? It isn't set to null, but rather not referenced anymore. 它没有设置为null,而是不再引用。 I'm not exactly sure how this is handled. 我不确定如何处理。 I'd like to think that because it isn't referenced anymore, it'd be garbage collected, but then again, the Profile isn't null. 我想考虑一下,因为不再引用它了,所以将其进行垃圾回收,但是再说一次,该配置文件也不为空。

Thank you. 谢谢。

The Profile object will become eligible for garbage collection when you remove it from the map, iff nothing else references it. 当您从地图上删除Profile对象时,只要其他对象都没有引用它,它就可以进行垃圾回收。 After that the garbage collector may or may not garbage collect it right away depending on how long the object has been referenced. 之后,垃圾回收器可能会立即垃圾回收,也可能不会立即垃圾回收,具体取决于引用对象的时间。

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

However for your purposes I suggest you simply remove it from the map, make sure it's not referenced anywhere else, and then don't worry about the finer details of how the garbage collector works. 但是,出于您的目的,我建议您仅将其从地图中删除,确保未在其他任何地方引用它,然后不必担心垃圾收集器如何工作的更详细信息。

The Profile object should be garbage collected however we don't know when GC will run hence it may possible that you may still have access to removed Profile object. Profile对象应该被垃圾回收,但是我们不知道GC何时运行,因此您可能仍然可以访问已删除的Profile对象。 But as soon as GC run and it find any unreferenced object then it will remove from the heap. 但是,一旦GC运行并找到任何未引用的对象,它就会从堆中删除。

https://dzone.com/articles/jvm-and-garbage-collection https://dzone.com/articles/jvm-and-garbage-collection

Use java.lang.System.gc(),this method runs the garbage collector.Calling this method suggests JVM(Java Virtual Machine) to start garbage collection, this method might clear the object might not too, that decision is left to the JVM. 使用java.lang.System.gc(),此方法运行垃圾收集器。调用此方法建议JVM(Java虚拟机)启动垃圾收集,此方法可能会清除对象,但可能不会,因此将决定权留给了JVM 。 The JVM operation might vary according to the OS platforms.So only thing you can possibly do is suggest the JVM to garbage collect. JVM的操作可能因操作系统平台而异,因此您唯一可以做的就是建议JVM进行垃圾回收。

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

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