title: ByteBuffer not releasing memory
body: <p>On Android, a direct ByteBuffer does not ever seem to release its memory, not even when calling System.gc(). </p>
  
  <p>Example: doing</p>
  
  <pre><code>Log.v("?", Long.toString(Debug.getNativeHeapAllocatedSize()));
  ByteBuffer buffer = allocateDirect(LARGE_NUMBER);
  buffer=null;
  System.gc();
  Log.v("?", Long.toString(Debug.getNativeHeapAllocatedSize()));
  </code></pre>
  
  <p>gives two numbers in the log, the second one being at least LARGE_NUMBER larger than the first.</p>
  
  <p>How do I get rid of this leak?</p>
  
  <hr>
  
  <p><strong>Added:</strong></p>
  
  <p>Following the suggestion by Gregory to handle alloc/free on the C++ side, I then defined</p>
  
  <pre><code>JNIEXPORT jobject JNICALL Java_com_foo_bar_allocNative(JNIEnv* env, jlong size)
      {
      void* buffer = malloc(size);
      jobject directBuffer = env-&gt;NewDirectByteBuffer(buffer, size);
      jobject globalRef = env-&gt;NewGlobalRef(directBuffer);
      return globalRef;
      }
  
  JNIEXPORT void JNICALL Java_com_foo_bar_freeNative(JNIEnv* env, jobject globalRef)
      {
      void *buffer = env-&gt;GetDirectBufferAddress(globalRef);
      free(buffer);
      env-&gt;DeleteGlobalRef(globalRef);
      }
  </code></pre>
  
  <p>I then get my ByteBuffer on the JAVA side with</p>
  
  <pre><code>ByteBuffer myBuf = allocNative(LARGE_NUMBER);
  </code></pre>
  
  <p>and free it with</p>
  
  <pre><code>freeNative(myBuf);
  </code></pre>
  
  <p>Unfortunately, while it does allocate fine, it a) still keeps the memory allocated according to <code>Debug.getNativeHeapAllocatedSize()</code> and b) leads to an error </p>
  
  <pre><code>W/dalvikvm(26733): JNI: DeleteGlobalRef(0x462b05a0) failed to find entry (valid=1)
  </code></pre>
  
  <p>I am now thoroughly confused, I thought I at least understood the C++ side of things... Why is free() not returning the memory? And what am I doing wrong with the <code>DeleteGlobalRef()</code>?</p>