Manuel Schmidt
Manuel Schmidt

Reputation: 2489

Tell the JVM how much native memory is used

My questions is strongly related to Java-Native-Code-Background:

You cannot control native memory from Java really well. You might have heard about native buffers, but what they haven’t told you is that Java doesn’t properly garbage native buffers. The problem is that Java doesn’t take the size of the native buffers into account, meaning that it will at some point free a native buffer, but if you have really many of those, then it probably won’t be before you run out of memory. This means that all data has to be stored in Java objects.

Therefore, is it possible to somehow tell or register the amount of native memory used in order to tell the JVM that it should run GC? If I understood it correctly, then Dalvik does this, but it would be nice to have a reliable way to do so on all JVMs.

Thanks!

Upvotes: 1

Views: 860

Answers (1)

Pavel Zdenek
Pavel Zdenek

Reputation: 7293

You can't tell JVM how much native memory is used, JVM simply doesn't have any interface for that. But if you simply don't want to run out of memory because JVM didn't notice how much have you used, i can think of two methods:

  1. force running GC with java.lang.System.gc() whenever you think that JVM should do. Smarter people than me are suggesting it. Don't forget that GC takes its toll on JVM performance.
  2. allocate one big direct buffer enough for the peak total usage of your application, make it persistent and do your own memory management on it. This is suggested by the NIO doc itself, on the grounds of higher de/alloc cost of direct buffer. Reuse it. Read and write your partial ByteBuffers at offsets of the big buffer.

Upvotes: 2

Related Questions