Search code examples
javamemorygarbage-collection

Garbage collection for a simulation that creates a lot of instances


I'm creating a falling sand game. This means there will be a lot of instances representing each individual element and lots of elements will be destroyed.

It would be a 2d array such as Element[][].

I'm writing this in Java so when I delete an element (Unassign it from the 2d array) it will still remain in memory until garbage collected. Eventually the memory would creep up until garbage collection kicks in which would freeze up the game.

I would like to avoid any freezing up and prefer if the memory usage could remain lower. Something that could work is if the garbage collector could run periodically or similar.

Overall I'm not sure if my app is going to be possible in Java if I can't get around this.

Is there a preferred garbage collector for this scenario or any other method I could use for handling this?


Solution

  • JVM does not allow you to run garbage collection on demand. You can try calling System.gc() but it will only suggest (as stated in the documentation) the JVM to run a FullGC.

    The JVM offers a variety of collectors

    Serial and parallel collectors use a Stop The World approach so they will freeze your game when running.

    G1 collector tries to balance between latency and throughput.

    I understand from your question you are looking for a low-latency garbage collection, so the user will not notices the pauses. I would suggest one of these collectors

    As they claim to be low-latency with sub-millisecond pauses.

    Using the JVM you will not be able to avoid gc pauses. They will eventually happen, but choosing the right GC can reduce their duration and occurrences. So maybe Java is not suitable for this use case.

    About keeping your memory usage low, that is up to you. Garbage collection can not help you with that. Just be really careful when allocating objects.