如何保持Java对象的存活? [英] How to keep alive Java objects?

查看:170
本文介绍了如何保持Java对象的存活?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑一种方法来防止垃圾收集中的Java对象,即使它没有在合理的时间内被引用。

I'm just thinking about a way of keeping away Java objects from garbage collection even if it is not being referred for a reasonable amount of time.

如何那样做?

推荐答案

在主类中有一个 static 容器你把对象的引用放入。它可以是 Map List ,等等。然后你将总是有一个对象的引用,它将不会被回收。 (为什么你想要这样做是另一个问题......)

Have a static container in your main class that you put a reference to the objects in. It can be a Map, List, whatever. Then you'll always have a reference to the object, and it won't be reclaimed. (Why you would want to do this is another question...)

这就是说:只要一个可达的参考对象存在,不会被垃圾收集。如果您的代码有引用并尝试使用它,那么该对象就在那里。你没有做任何特别的事情来实现这一点(你也不应该)。 (可达引用意味着引用来自某些东西,它本身可以从它引用的东西以外的东西到达。更简单地说:GC理解循环引用,因此可以清理A和B即使他们互相引用,只要没有其他任何内容引用他们中的任何一个。)

Which is to say: As long as a reachable reference to an object exists, it will not be garbage-collected. If your code has a reference and tries to use it, the object will be there. You don't have to do anything special to make that happen (nor should you). (A reachable reference means that the reference is from something that is, itself, reachable from something other than the things it references. Put more simply: The GC understands about circular references and so can clean up A and B even if they refer to each other, as long as nothing else refers to either of them.)

这篇关于如何保持Java对象的存活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆