另一个强制Java垃圾收集问题(*我认为*一个合理的用例) [英] Another Forcing Java Garbage Collection Question (with *I think* a justifiable use case)

查看:95
本文介绍了另一个强制Java垃圾收集问题(*我认为*一个合理的用例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据生产者,可以生成许多不同消费者使用的数据(我们称之为Cs)。每个C都有它自己感兴趣的一组数据。数据生成器对C的引用很弱,因此可以通知它们更新。

每个C也被使用由许多独立的组件组成,因此没有一个组件可以告诉C何时不再需要,因此我们必须将其留给JVM以确定C何时可以使用GC。



这里的目标是在C过时时被通知,因此数据生产者可以关闭那些只对那些未使用的C感兴趣的数据。

正如我前面提到的那样,数据生产者总是对C的引用很弱,所以当C被GCC处理时很容易做到。但是,我注意到Cs通常会在VM中停留很长一段时间,然后才会最终进行GC编辑,而此时数据生产者正在生产大量所需的数据。



有什么方法可以强制未使用的Cs的GC?我希望是的,但我期待着一个否,所以作为一个后续问题,有没有人有一个好的建议,我怎么可以(重新)设计这个,使其更好/更有效地工作?



谢谢!!



下面的一些答案提供了很多好处 - 特别是强制C用户的建议订阅和取消订阅。这很困难,因为:

C只是接口I的一种可能实现(它没有此订阅要求),这是用户真正使用的。 C实现是在运行时注入的,因此我们不能强制用户遵守C特定的要求。 (Ouch?)

解决方案

我只想用System.gc();



在这篇相关文章中有一些非常有趣的信息:
Java:你如何真的使用JVMTI的ForceGargabeCollection强制GC?



显然很多IDE也使用它评估可用堆的数量。猜猜我没有理由不这样做。


I have a data producer that produces data that is used by a number of a different consumers (let's call them Cs). Each C has its own set of data that it's interested in. The data producer has weak references to the Cs so they can be notified for updates.

Each C is also used by a number of independent components, so no single one component can tell when the C is no longer needed, so we have to leave it to the JVM to determine when C is GC-able.

The goal here is to be notified when a C becomes obsolete, so the data producer can turn off data that is only interesting to that unused C.

As I mentioned earlier, the data producer always has weak references to the Cs, so it's easy to do it when a C is GCed. However, I noticed that the Cs usually stick around in the VM for an extended period of time before it's finally GC-ed and all this while, the data producer is producing a LOT of data it should have needed to.

Is there any way for me to force the GC of unused Cs? I am hoping for yes, but I'm expecting a No, so as a follow-up question, does anyone have a good suggestion to how I can (re)design this to make it work better/more efficiently?

Thank you!!

Some answers below make a lot of good points - in particular the suggestion to force users of C to subscribe and unsubscribe. This is difficult because:

C is just one possible implementation of an interface I (which doesn't have this subscription requirement), which is what the users really use. The C implementation is injected during run-time, so we can't force the users to comply to C-specific requirements. (Ouch?)

解决方案

I'll just go with System.gc();

There's some really interesting information in this related post: Java: How do you really force a GC using JVMTI's ForceGargabeCollection?

Apparently a lot of IDEs use that too to evaluate the amount of available heap. Guess there's no reason I can't do that too.

这篇关于另一个强制Java垃圾收集问题(*我认为*一个合理的用例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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