Skip to content
Advertisement

How to properly close MappedByteBuffer?

This is the code I’m running:

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

public class Main {
    public static void main(String[] args) throws Exception {
        String filePath = "D:/temp/file";
        RandomAccessFile file = new RandomAccessFile(filePath, "rw");

        try {
            MappedByteBuffer buffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 128);

            // Do something
            buffer.putInt(4);
        } finally {
            file.close();
            System.out.println("File closed");
        }

        System.out.println("Press any key...");
        System.in.read();

        System.out.println("Finished");
    }
}

Before pressing a key, I’m trying to delete the file manually in FAR Manager. But FAR says that the file is locked:

 The process cannot access the file because it is being used by another process.
                     Cannot delete the file
                         D:tempfile
                    Object is being opened in:
 Java(TM) Platform SE binary (PID: 5768, C:Program FilesJavajdk1.8.0_05binjavaw.exe)

Only after pressing a key, the application terminates and I can delete the file.

What is wrong with my code?

Advertisement

Answer

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");
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement