Reputation: 11688
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.
Upvotes: 0
Views: 910
Reputation:
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 -Xms
and -Xmx
command line arguments to java
. 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.
Java HotSpot includes three different collectors. The serial collection uses a single thread for GC and is best suited for single processor machines with data sets smaller than 100 Mbytes. The parallel performs minor collections in parallel. It is ideally suited for medium to large datasets running on multi-threaded or multi-processor hardware. The concurrent collector has been optimized to garbage collection pauses short when response time is more important than throughput. This mode does not normally provide any benefit on a single-core machine.
To avoid OutOfMemoryExceptions
Set -Xmx
to as large a setting as you can afford on your server. Set -Xms
to the minimum size of block of memory you think is nominal. Too small is worse than too big.
Don't leak references.
Upvotes: 4