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() 应该可以获取锁进行写同步。
桂棹兮兰桨,击空明兮溯流光。