I’m using java to build a socket server.
I’m logging lots of actions which are happening during the server run,
and beside each log line I’m writing the current free memory in the JVM using the:
Runtime.getRuntime().freeMemory()
as I can see in my log, I don’t have lots of free memory (around 14-15 MB).
I run this socket server on a freeBSD server with root access.
I really want to tune up the memory allocated to my JVM but I don’t really know how, and I’m pretty new to freeBSD and linux in general.
You assumption about how memory works ( especially Garbage Collection ) in Java is flawed.
Runtime.getRuntime().freeMemory().That call only shows “free” memory on the JVM heap, which is allocated with the
-Xmsand-Xmxcommand line arguments tojava. Or in some startup script if you are using an app server.Why what you are trying to do is a waste of time
See this answer to this question why!
The Garbage Collector in Java ( which controls free memory ) isn’t tuned to keep as much memory free as possible, it is tuned for a balance of performance and responsiveness. It only frees memory on demand, there is no benefit in having max free memory and lots of downsides to trying to do so.
This causes objects that aren’t referenced anymore to hang around “using memory” until the memory they occupy is actually needed. This is actually optimal because prematurely removing them would cause performance degradation of the running code.
Removing them very quickly only when memory needs to be freed is the goal of the Garbage Collector not trying to keep as much memory free as possible.
You should never have to call
System.gc()in a correctly implemented Java program.To avoid OutOfMemoryExceptions
Set
-Xmxto as large a setting as you can afford on your server. Set-Xmsto the minimum size of block of memory you think is nominal. Too small is worse than too big.Don’t leak references.