Search code examples
javagarbage-collectionprofilingjitvisualvm

Is JIT capable to optimize memory allocation?


This is GC diagram from visualvm for a simple application that listens for some incoming stream of data trough websocket... At start it creates a lot of garbage, but as you can see it gets better over time... Is this JIT figuring out somehow how to avoid creating objects?

enter image description here


Solution

  • There are some very specific cases, where the JIT can remove allocations and therefore reduce the pressure on the GC. Mainly with escape analysis. Basically if the object lives only withing one method and never leaves it, it can be allocated on the stack instead of the heap, reducing work of the garbage collector. If you want to know for sure: You can disable escape analysis: Use the command line argument -XX:-DoEscapeAnalysis and see if the graph changes.

    However there many other self tuning mechanisms present. Like the runtime system notices that you don't need as much memory, and therefore start to reduce the heap size. Your graph would match that. As most of the memory can always be freed, the memory system reduces the heap size: With more frequent but smaller GC's.