Burst memory usage in Java

前端 未结 8 2190
臣服心动
臣服心动 2021-02-03 23:57

I am trying to get a handle on proper memory usage and garbage collection in Java. I\'m not a novice programmer by any means, but it always seems to me that once Java touches so

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 00:28

    I ran into this problem on Windows and have found a solution, so I'm posting it as an answer in case it can help others.

    A lot of answers on here suggest that Java's behavior is 1. good and/or 2. an unavoidable consequence of garbage collecting. These are both false.

    The Problem:

    If you are like me and you want to write Java to write small applications for a workstation or even run multiple smaller processes on a server, then Oracle's JVM memory allocation behavior makes it almost completely useless. Even when running with -client, every JVM process hoards memory once allocated and never gives it back. This behavior cannot be disabled. As the OP notices: each jvm process holds on to its unused memory indefinitely even if it will never use it again and even while other jvm processes are starving. This inexplicable behavior makes Oracle's a useless implementation for all but monolithic, single-application scenarios.

    Also: this is NOT a consequence of garbage collection. Witness .Net applications which run on Windows, use garbage collection, and do not suffer from this problem at all.

    The Solution:

    The solution I found to this was to use the IKVM.NET JVM which you use as a drop-in replacement for java.exe on windows. It compiles Java bytecode to .Net IL code and runs as a .Net process. It also contains utilities to convert .jar files into .Net .dll and .exe assemblies. The performance is often better than Oracle's JVM and after a GC, memory is instantly returned to the OS. (Note: this also works in Linux with Mono)

    To be clear, I still rely on Oracle's JVM for all but my small applications and also to debug my small applications, but once stable, I use ikvm to run them as if they were native windows applications and this works so well, I've been amazed. It has numerous beneficial side effects. Once compiled, DLLs shared between processes are loaded only once, and applications show up in the task manager as .exe instead of all showing as javaw.exe.

    Unfortunately, not everyone can use ikvm to solve this problem, but I hope this helps those in my situation.

提交回复
热议问题