GC.AddMemoryPressure equivalent in Java

Project: Java, JNI (C ++), Android.

I am going to manage my own C ++ life time by creating a managed wrapper class that will contain a pointer to my own object (as a long member) and delete the override finalize () method in it. See this question for more details.

A C ++ object does not use other types of resources, but only memory. The memory size of the object is not very high, but it is significantly higher than 64 bits in Java. Is there a way to tell the Java GC that my wrapper is not only responsible for the long value, but it is also not worth creating millions of such objects before running the garbage collector? In .NET, there is the GC AddMemoryPressure () method, which exists for exactly this purpose. Is there an equivalent in Java?

+6
source share
2 answers

After a few more searches, I found a good article at the IBM Research Center.

In short, they recommend using a bunch of Java instead of their own heap for their own objects. Thus, the memory pressure on the JVM garbage collector is more realistic for native objects referenced by Java code through descriptors.

To achieve this, you need to override the default C ++ memory allocation and deletion functions: the new operator and the delete operator. In the new operator, if the JVM is available (JNI_OnLoad has already been called), then it calls NewByteArray and GetByteArrayElements, which returns the allocated memory. To protect the ByteArray created from garbage collection, you must also create a NewGlobalRef for it and save it, for example. in the same allocated memory block. In this case, we need to allocate as much memory as requested, plus memory for the links. In operator deletion, delete DeleteGlobalRef and ReleaseByteArrayElements. If the JVM is not available, it uses its own malloc and free functions.

+4
source

I believe that native memory is allocated outside the Java heap volume. So you don’t have to worry about your allocation taking up memory away from the value you reserved with -Xmx<size> .

With this, you can use ByteBuffer.allocateDirect () to allocate a buffer and GetDirectBufferAddress to access it from your own code. You can control the heap size of direct memory with -XX:MaxDirectMemorySize=<size>

+1
source

Source: https://habr.com/ru/post/892887/


All Articles