开发者

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.

So I thought, maybe if a called gc less frequent? 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 w开发者_StackOverflow中文版ould throw an outOfMemory exception anyways.

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? 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.

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.


The pause is probably garbage collection happening. As Frederik mentions, are you sure you have to invoke the GC manually? 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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜