简体   繁体   English

System.gc问题

[英]System.gc problem

I'm running a scheduling algorithm with a garbage collection snippet that looks like this: 我正在运行一个带有垃圾收集代码段的调度算法,如下所示:

    //garbage collection
    if (state.children.isEmpty()) {//if this is a leaf node (no children)
        state.parent.children.remove(state);
        System.gc();
    }

At first, the algorithm runs smoothly with no pauses; 首先,该算法运行平稳,没有任何暂停; but after a while as the tree starts getting bigger, there's some sort of pause at each gc. 但是过了一会儿,随着树开始变大,每个gc都有某种暂停。

So I thought, maybe if a called gc less frequent? 所以我想,也许一个叫做gc的频率降低? And modified my code to this: 并将我的代码修改为:

    //garbage collection
    if (state.children.isEmpty()) {//if this is a leaf node (no children)
        state.parent.children.remove(state);
        if(index % 10000)
            System.gc();
    }

But this doesn't seem to actually do any cleanup, my program would throw an outOfMemory exception anyways. 但这似乎并没有进行任何清理,我的程序无论如何都会抛出outOfMemory异常。

How should I implement my garbage collector correctly so as not to be called too many times? 我应该如何正确实现我的垃圾收集器,以免被调用过多?

You shouldn't need to call the garbage collector explicitly at all. 您根本不需要显式调用垃圾收集器。 It's very occasionally appropriate, but I would normally be pretty suspicious if you find you need it. 有时候合适,但是如果您发现需要它,我通常会非常怀疑。

Have you tried running with detailed GC logging turned on? 您是否尝试过在打开详细的GC日志记录的情况下运行? It can be awkward to understand at first, but it should show you what's going on. 一开始可能很难理解,但是它应该告诉您发生了什么。 I wouldn't be surprised to find that actually you've got a leak somewhere, and it's just that by GC-ing on every iteration, you've slowed your program down enough so that you just haven't reached the point at which it bites. 我不会惊讶地发现实际上您的某个地方存在泄漏,只是通过在每次迭代中进行GC运算,您已将程序的速度降低了足够慢,以至于您还没有达到它咬。

How much memory have you allocated for the VM? 您为虚拟机分配了多少内存? Tweaking the memory settings (and indeed the GC settings) can have a big impact on some workloads. 调整内存设置(实际上是GC设置)可能会对某些工作负载产生很大影响。

The pause is probably garbage collection happening. 暂停可能正在发生垃圾回收。 As Frederik mentions, are you sure you have to invoke the GC manually? 正如Frederik所述,您确定必须手动调用GC吗? Generally you shouldn't need to. 通常,您不需要。 If you're concerned about your memory usage, feel free to prune your tree more often, but let the GC handle when to run, and don't invoke it manually. 如果您担心内存的使用情况,请随时更频繁地修剪树,但是让GC处理何时运行,不要手动调用它。

You mentioned that your second snippet results in OutOfMemoryExceptions though, so maybe you have some other problems going on, you might want to show some more code. 您提到您的第二个片段虽然会导致OutOfMemoryExceptions,所以也许您还遇到其他一些问题,您可能想显示更多代码。

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

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