当前位置:科普知识站>IT科技>

java|mmap

IT科技 阅读(1.84W)

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

java mmap是什么,让我们一起了解一下?

mmap是将一个文件或者其它对象映射进内存,文件被映射到多个页上,如果文件的大小不是所有页的大小之和,最后一个页不被使用的空间将会清零。mmap在用户空间映射调用系统中作用很大。

目前Java提供的mmap只有内存文件映射,其他IO操作还没有内存映射功能。

Java内存映射文件(Memory Mapped Files)就已经在java.nio包中,但它对很多程序开发者来说仍然是一个相当新的概念。引入NIO后,Java IO已经相当快,而且内存映射文件提供了Java有可能达到的最快IO操作,这也是为什么那些高性能Java应用应该使用内存映射文件来持久化数据。

mmap在Java中的用途是什么?

1、对普通文件使用mmap提供内存映射I/O,以避免系统调用(read、write、lseek)带来的性能开销。同时减少了数据在内核缓冲区和进程地址空间的拷贝次数。

java mmap

2、使用特殊文件提供匿名内存映射。

3、使用shm_open以提供无亲缘关系进程间的posix共享内存区。

mmap在Java中是如何使用的?(具体参考kafka源码中的OffsetIndex这个类)

操作文件,就相当于操作一个ByteBuffer一样。

public class TestMmap {undefinedpublic static String path = "C:Users64371Desktopmmap";public static void main(String[] args) throws IOException {undefinedFile file1 = new File(path, "1");RandomAccessFile randomAccessFile = new RandomAccessFile(file1, "rw");int len = 2048;// 映射为2kb,那么生成的文件也是2kbMappedByteBuffer mmap = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, len);System.out.println(mmap.isReadOnly());System.out.println(mmap.position());System.out.println(mmap.limit());// 写数据之后,JVM 退出之后会强制刷新的mmap.put("a".getBytes());mmap.put("b".getBytes());mmap.put("c".getBytes());mmap.put("d".getBytes());// System.out.println(mmap.position());// System.out.println(mmap.limit());//// mmap.force();// 参考OffsetIndex强制回收已经分配的mmap,不必等到下次GC,unmap(mmap);// 在Windows上需要执行unmap(mmap); 否则报错// Windows won't let us modify the file length while the file is mmapped// java.io.IOException: 请求的操作无法在使用用户映射区域打开的文件上执行randomAccessFile.setLength(len/2);mmap = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, len/2);// A mapping, once established, is not dependent upon the file channel// that was used to create it. Closing the channel, in particular, has no// effect upon the validity of the mapping.randomAccessFile.close();mmap.put(128, "z".getBytes()[0]);}// copy from FileChannelImpl#unmap(私有方法)private static void unmap(MappedByteBuffer bb) {undefinedCleaner cl = ((DirectBuffer)bb).cleaner();if (cl != null)cl.clean();}}