java 通过 nmap 跨进程内存共享

先启动A进程,再启动B进程。

A进程:

复制代码
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class ProgramA {

    public static void main(String[] args) throws IOException {
        FileChannel fileChannel = new RandomAccessFile(new File("db.data"), "rw").getChannel();
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 8);
        
        //
        byte[] data = new byte[] {3,3,3,3,4,4,4,4};
        mappedByteBuffer.put(data);
        
        System.out.println("数据写入成功!");
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        reader.readLine();
        
        System.out.println("over");
        fileChannel.close();
    }

}
复制代码

 

B进程:

复制代码
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class ProgramB {

    public static void main(String[] args) throws IOException {
        FileChannel fileChannel = new RandomAccessFile(new File("db.data"), "rw").getChannel();
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 8);

        //
        byte[] data = new byte[8];
        ByteBuffer subBuffer = mappedByteBuffer.slice();
        subBuffer.get(data);
        System.out.println("数据读取成功:");
        System.out.println(data);
        fileChannel.close();
    }

}
复制代码

 如果要从指定位置读取或写入:

MappedByteBuffer subBuffer = mappedByteBuffer.slice(); 
subBuffer.position(position); 
subBuffer.put(data);
subBuffer.sett(data);

通过测试发现,内存区没有做写同步互斥,多个进程可以同时往一块内存同时写入数据,这种使用方式可能会导致内存损坏。.getChannel().lock() 应该可以获取锁进行写同步。

posted on   空明流光  阅读(350)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示