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