首页 > 移动平台 > 详细

内存映射文件MappedByteBuffer

时间:2019-08-14 21:04:01      阅读:98      评论:0      收藏:0      [点我收藏+]

上一篇讲到的DirectByteBuffer继承自MappedByteBuffer

MappedByteBuffer的定义:

A direct byte buffer whose content is a memory-mapped region of a file.

直接缓存,内容是一个内存映射文件。

创建测试类

public class NioTest9 {
    public static void main(String[] args) throws  Exception {
        RandomAccessFile randomAccessFile = new RandomAccessFile("NioTest9.txt","rw");
        FileChannel fileChannel =  randomAccessFile.getChannel();
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0,5);
        mappedByteBuffer.put(0,(byte)‘a‘);
        mappedByteBuffer.put(3,(byte)‘b‘);

        randomAccessFile.close();
    }
}

 创建NioTest9.tex文件

技术分享图片

 

 运行程序,用记事本打开

技术分享图片

操作的是堆外内存,堆外内存写入到文件由操作系统控制。

 

二、排他锁和共享锁

实际用的比较少

/**
 * 
 * 共享锁: 所有程序都能多共享的部分进行读
 * 排他锁: 只有一个程序对锁定的部分进行写操作
 * 
 */
public class NioTest10 {

    public static void main(String[] args) throws Exception {
        RandomAccessFile randomAccessFile = new RandomAccessFile("NioTest10.txt", "rw");

        FileChannel fileChannel = randomAccessFile.getChannel();

       FileLock fileLock = fileChannel.lock(3,6,true);

        System.out.println("valid:" + fileLock.isValid());

        System.out.println("lock type:" + fileLock.isShared());

        fileLock.release();

        randomAccessFile.close();
    }
}

  

内存映射文件MappedByteBuffer

原文:https://www.cnblogs.com/linlf03/p/11354571.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!