Problem description
Memory-mapped concepts are now used in many Java code. The method of file mapping is much faster than the way the output stream is entered. However, when you use the force and close methods of FileChannel normally, you will fail to rename the files or delete them. The main reason is that the handle to the file is not released. Caused by
Problem Analysis and Solution
If the file handle is held, it is equivalent to a pointer to a file in the JVM virtual machine, so renaming the file and deleting the file will result in a failure. Mappedbytebuffer does not provide a unmap method, and the bug in the JDK about this unmap method is always open. The most common way to find out online is to use reflection to call Filechannelimpl's Unmap method to free memory:
privatestaticvoidunmap(MappedByteBuffer var0) { Cleaner var1 = ((DirectBuffer)var0).cleaner(); ifnull) { var1.clean(); } }
The code for the reflection call is not written. And personally tested it can certainly guarantee the deletion of files.
The reason for calling with reflection is that this method is private and static. But in a different way, since we already know the implementation of internal code, it's better to write a unmap method to copy the internal code. So
privatevoidunmap(MappedByteBuffer var0) { Cleaner var1 = ((DirectBuffer)var0).cleaner(); ifnull) { var1.clean(); } }
After calling the force method in buffer, you can rename the file by calling the Unmap method.
new".txt"new RandomAccessFile(file,"rw");FileChannel channel = raf.getChannel();MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE4);buffer.force();channel.force(true);channel.close();raf.close();unmap(buffer)
You can use the rename () method to test if the file is occupied
file.rename(file)
Returns true renaming succeeded, false renaming of file failed.
Special cases
If buffer has insufficient capacity, a Mappedbytebuffer object needs to be regenerated with channel.map (), and the Buffer.force () method and the Unmap (buffer) Two methods should be called before the new buffer is mapped. Otherwise, the file cannot be renamed or deleted. The reason should be that the objects in the heap were not recycled by buffer and still hold the handle to the file.
Mappedbytebuffer file Handle Release problem