2

In Java, Runtime.getRuntime.freeMemory() occasionally returns a negative number - why?

It possibly seems to happen more with busy/memory gobbling code.

This must have been answered elsewhere, but my searching-fu is failing me.

I am running with Oracle Windows 64bit JVM - 1.7.0_80. Also see this with the OpenJDK, Linux version - 1.7.0_85 (64bit) - although as I watch it now, its negative for the maxMemory and totalMemory calls - freeMemory is positive.

Using ParNew/ConcurrentMarkSweep garbage collectors.

Chris Kimpton
  • 5,546
  • 6
  • 45
  • 72
  • 2
    Possible duplicate of [Negative Free Memory](http://stackoverflow.com/questions/5812785/negative-free-memory) – user2390182 Nov 26 '15 at 09:36
  • 1
    Well, the javadoc of the method _does_ say that what is returned is an "approximation"... If you want more precise measures you should probably have a look at JMX instead – fge Nov 26 '15 at 09:37
  • @schwobaseggl, no, that question is different: it's about difference between *two* `freeMemory()` calls. – Tagir Valeev Nov 26 '15 at 09:39
  • @TagirValeev True! The title of the other question is rather misleading though – user2390182 Nov 26 '15 at 09:42
  • 1
    The [actual implementation](http://hg.openjdk.java.net/jdk8/jdk8/hotspot/file/87ee5ee27509/src/share/vm/prims/jvm.cpp#l453) is the difference between `heap->capacity()` and `heap->used()`. The difference is calculated under the Heap lock, so race is unlikely here. Probably some glitch in GC implementation. Which garbage collector are you using (try to switch to another one and check)? And which JVM version? – Tagir Valeev Nov 26 '15 at 09:44
  • 1
    The Java docs do state that the calculation is an approximation; so this is sounding like a quirk of that approximation which is free to change between JVM vendors and versions. When this occurred, was the heap near capacity and the GC kicking in? If so, you were probably seeing the result of some allocations coming in after memory being freed that were not yet fully visible within the approximate value returned by freeMemory(). – Chris K Nov 26 '15 at 09:53

1 Answers1

1

Whoops - this is a bit embarrassing.

I was monitoring it via a tool that was holding the numbers as INT - hence large numbers were wrapping/going negative :(

Apologies for wasting your time :(

Chris Kimpton
  • 5,546
  • 6
  • 45
  • 72