How Java Works


Running java program

When you run a java program, a few things happen. Your java installation creates a virtual machine (JVM). That virtual machine now handles your program. This means that outside process monitors will report the resource usage of the JVM, not your program that runs inside that. In addition, because it runs inside a JVM, your program will need additional resources to operate. This means, for example, that if your program has -Xmx set to 4G, your program will take up to 4gb of memory for heap, and then a bit more for managing the JVM itself. This overhead depends on a lot of different factors and can reach up to few gigabytes.

Garbage Collection

While running, your java program will allocate memory inside of its JVM by creating new objects and working on them. When an object is no longer used (program no longer references it) it's not immediately removed. Instead, every so often GC is engaged and depending on type of GC configured, it executes a strategy to remove unused objects. This usually involves pausing your program for the duration of the check and removal GC phase. This means that in most cases allocating more memory than needed can hurt your program's performance, due to GC having to take more time to clean up more memory.

Memory leaks

Memory leaks in java applications happen when a program saves an object and keeps reference to it, for example it can add an element to the list when user logs in, but never removes it when user logs out. This causes that list to grow and take up more and more space in the heap memory until heap memory runs out and application crashes with Out Of Memory (OOM) error. The speed of the memory buildup can vary with the amount and speed of information added to the tracked data.