BeiKeJieDeLiuLangMao / HexoBlogComment

Use this repository to save blog comments
0 stars 0 forks source link

RocketMQ 内存映射 | 贝克街的流浪猫 #147

Open BeiKeJieDeLiuLangMao opened 4 years ago

BeiKeJieDeLiuLangMao commented 4 years ago

https://www.beikejiedeliulangmao.top/middleware/rocketmq/memory-map/

引言前面我们已经简单地介绍了 RocketMQ 的整体设计思路,本文着重其中使用到的内存映射相关内容,更多关于 RocketMQ 的文章均收录于<RocketMQ系列文章>;

lecssmi commented 2 years ago

我发现一个问题,使用mmap不一定比传统的RandomAccessFile快。 public static void createFileWithMap() throws Exception{

    Long start=System.currentTimeMillis();
    RandomAccessFile file = new RandomAccessFile("map.txt", "rw");
    MappedByteBuffer buffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE,0,Integer.MAX_VALUE);

    Integer maxLoop=Integer.MAX_VALUE/4096;
    byte[] bytes=new byte[4096];
    for(int i=0;i<4096;i++){
        bytes[i]=(byte)67;
    }
    for (int i=0;i<maxLoop;i++){
        buffer.put(bytes);
    }

// buffer.force(); file.close(); System.out.println("map write file cost " +(System.currentTimeMillis()-start) +" ms");

}

public static void createFileWithFile() throws Exception{

    Long start=System.currentTimeMillis();
    RandomAccessFile file = new RandomAccessFile("file.txt", "rw");
    file.seek(0);

    Integer maxLoop=Integer.MAX_VALUE/8192;
    byte[] bytes=new byte[8192];
    for(int i=0;i<8192;i++){
        bytes[i]=(byte)67;
    }
    for (int i=0;i<maxLoop;i++){
        file.write(bytes);
    }
    file.close();
    System.out.println("file write file cost " +(System.currentTimeMillis()-start) +" ms");

}

在windows上,mmap不调用force方法的话,非常快。但是在linux上,同样的条件下,mmap慢多了。