Unmapping or 'release' a MappedByteBuffer under Android

筅森魡賤 提交于 2019-12-08 15:31:55

问题


The usual problem in Java is that you have to hack to get a proper unmapping of memory mapped files - see here for the 14year old bug report ;)

But on Android there seems to be 0 solutions in pure Java and just via NDK. Is this true? If yes, any pointers to an open source solution with Android/Java bindings?


回答1:


There is no hack available under Android.

But there are a few helpers and snippets which make the C-Java binding for mmap files easy/easier:

  • util-mmap, Apache License 2.0, here is an issue regarding Android support
  • Using Memory Mapped Files and JNI to communicate between Java and C++ programs or easier with tools like javacpp?
  • It looks tomcat has implement a helper (jni.MMap) that is able to unmap/delete a mmap file

See the util-mmap in action, really easy:

public class MMapTesting {

    public static void main(String[] args) throws IOException {
        File file = new File("test");
        MMapBuffer buffer = new MMapBuffer(file, 0, 1000, FileChannel.MapMode.READ_WRITE, ByteOrder.BIG_ENDIAN)) {
            buffer.memory().intArray(0, 100).set(2, 234);
        // calls unmap under the hood
        buffer.close();

        // here we call unmap automatically at the end of this try-resource block 
        try (MMapBuffer buffer = new MMapBuffer(file, FileChannel.MapMode.READ_WRITE, ByteOrder.BIG_ENDIAN)) {
            System.out.println("length: " + buffer.memory().length());
            IntArray arr = buffer.memory().intArray(0, buffer.memory().length() / 8);
            // prints 234
            System.out.println(arr.get(2));
        }
    }
}



回答2:


From the Android Developers website:

A direct byte buffer whose content is a memory-mapped region of a file.

Mapped byte buffers are created via the FileChannel.map method. This class extends the ByteBuffer class with operations that are specific to memory-mapped file regions.

A mapped byte buffer and the file mapping that it represents remain valid until the buffer itself is garbage-collected.

The content of a mapped byte buffer can change at any time, for example if the content of the corresponding region of the mapped file is changed by this program or another. Whether or not such changes occur, and when they occur, is operating-system dependent and therefore unspecified.

As for what I've understood from this text, is that there is no way to unmap the MappedByteBuffer using the Android Java SDK. Only using the NDK, like you said.



来源:https://stackoverflow.com/questions/38315292/unmapping-or-release-a-mappedbytebuffer-under-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!