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() 应该可以获取锁进行写同步。
桂棹兮兰桨,击空明兮溯流光。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!