Truncate memory mapped file

后端 未结 2 1812
眼角桃花
眼角桃花 2021-02-19 21:39

I am using memory mapped IO for an index file, but the problem is that I\'m not able to resize the file if it is mostly empty.

Somewhere before:

MappedB         


        
2条回答
  •  庸人自扰
    2021-02-19 22:13

    Your issue is that you are using unreliable method to close mapped byte buffer (one hundred calls to System.gc() and System.runFinalization() don't guarantee you anything). Unfortunately there is no reliable method in Java API to do that, but on Sun JVM (and perhaps on some others too) you can use the following code:

    public void unmapMmaped(ByteBuffer buffer) {
      if (buffer instanceof sun.nio.ch.DirectBuffer) {
        sun.misc.Cleaner cleaner = ((sun.nio.ch.DirectBuffer) buffer).cleaner();
        cleaner.clean();
      }
    }
    

    Of course it is JVM-dependent and you should be ready to fix your code if Sun ever decides to change sun.nio.ch.DirectBuffer or sun.misc.Cleaner in an incompatible manner (but actually I don't believe this will ever happen).

提交回复
热议问题