How to properly close MappedByteBuffer?

前端 未结 2 2065
一整个雨季
一整个雨季 2020-12-07 01:56

This is the code I\'m running:

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
         


        
相关标签:
2条回答
  • 2020-12-07 02:24

    @SANN3's answer doesn't work on Java 9 anymore. In Java 9 there is a new method sun.misc.Unsafe.invokeCleaner that can be used. Here is a working code:

    MappedByteBuffer buffer = ...
    
    // Java 9+ only:
    Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
    Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
    unsafeField.setAccessible(true);
    Object unsafe = unsafeField.get(null);
    Method invokeCleaner = unsafeClass.getMethod("invokeCleaner", ByteBuffer.class);
    invokeCleaner.invoke(unsafe, buffer);
    
    0 讨论(0)
  • 2020-12-07 02:29

    Try this one.

    public class Test
    {
        public static void main(String[] args) throws Exception {
            String filePath = "D:/temp/file";
            RandomAccessFile file = new RandomAccessFile(filePath, "rw");
            FileChannel chan = file.getChannel();
            try {
                MappedByteBuffer buffer = chan.map(FileChannel.MapMode.READ_WRITE, 0, 128);
    
                // Do something
                buffer.putInt(4);
                buffer.force();
                Cleaner cleaner = ((sun.nio.ch.DirectBuffer) buffer).cleaner();
                if (cleaner != null) {
                    cleaner.clean();
                }
            } finally {
                chan.close();
                file.close();
                System.out.println("File closed");
            }
    
            System.out.println("Press any key...");
            System.in.read();
    
            System.out.println("Finished");
        }
    }
    
    0 讨论(0)
提交回复
热议问题