Java中能否读取匿名/非持久化内存映射文件?Windows下可指定标签名吗?
Great question! Let's break this down clearly, since Java's standard NIO tools don't make this as straightforward as Python's mmap:
Can Java read/use anonymous non-persistent memory-mapped files?
Absolutely—but you can't do it directly with FileChannel#map, which only handles persistent mappings tied to disk files. You have a few viable options depending on your use case and Java version:
Option 1: Simulate anonymous mappings with temporary files (cross-platform)
You can create a temporary file, map it via FileChannel#map, then immediately delete the file (note: on Windows, you might need to delete it after unmapping, since the OS locks open files). While this isn't a true anonymous mapping (it still ties to a disk temp file), the file gets cleaned up once the last process exits, mimicking the behavior of anonymous shared memory. It's a quick cross-platform workaround, but not ideal for scenarios where you want zero disk overhead.
Option 2: Use Windows Native APIs (for named anonymous mappings)
If you specifically need Windows-style named anonymous mappings (like Python's mmap with -1 and a tag name), you'll need to call Windows kernel APIs directly. The easiest way to do this in Java is with JNA (Java Native Access) to wrap calls like CreateFileMappingW and OpenFileMappingW.
Here's a quick example of creating a named anonymous shared memory segment on Windows:
import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.platform.win32.WinBase; import com.sun.jna.platform.win32.WinNT; import com.sun.jna.platform.win32.WinPageProtect; public class WindowsNamedSharedMem { // Define JNA interface for kernel32.dll private interface Kernel32 extends Library { Kernel32 INSTANCE = Native.load("kernel32", Kernel32.class); WinNT.HANDLE CreateFileMappingW(WinNT.HANDLE hFile, WinBase.SECURITY_ATTRIBUTES lpAttributes, int flProtect, long maxSizeHigh, long maxSizeLow, String lpName); WinNT.HANDLE MapViewOfFile(WinNT.HANDLE hMap, int desiredAccess, long offsetHigh, long offsetLow, long numBytes); boolean UnmapViewOfFile(WinNT.HANDLE lpBaseAddress); boolean CloseHandle(WinNT.HANDLE hObject); WinNT.HANDLE OpenFileMappingW(int desiredAccess, boolean inheritHandle, String lpName); } public static void main(String[] args) { // Create a named anonymous mapping with tag "MY_JAVA_SHARED_MEM" WinNT.HANDLE mapHandle = Kernel32.INSTANCE.CreateFileMappingW( WinBase.INVALID_HANDLE_VALUE, // Mark as anonymous (no file handle) null, WinPageProtect.PAGE_READWRITE, // Read/write access 0, 1024 * 1024, // 1MB size "MY_JAVA_SHARED_MEM" // Unique tag name ); if (mapHandle == null) { System.err.println("Failed to create mapping: " + Native.getLastError()); return; } // Map the segment to memory WinNT.HANDLE memPtr = Kernel32.INSTANCE.MapViewOfFile( mapHandle, WinNT.FILE_MAP_ALL_ACCESS, 0, 0, 0 ); // Use the memory (write/read data here) // ... // Cleanup Kernel32.INSTANCE.UnmapViewOfFile(memPtr); Kernel32.INSTANCE.CloseHandle(mapHandle); } }
To use this, you'll need to add JNA dependencies to your project (e.g., for Maven):
<dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna</artifactId> <version>5.13.0</version> </dependency> <dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna-platform</artifactId> <version>5.13.0</version> </dependency>
Other processes (even non-Java ones) can access this same segment by using the exact tag name MY_JAVA_SHARED_MEM when calling OpenFileMappingW.
Option 3: Use Java 14+'s MemorySegment API (modern, cross-platform)
Starting with Java 14 (incubated, now stable in Java 17+), the java.lang.foreign API introduces MemorySegment and SharedSession, which let you create cross-process shared anonymous memory segments. This is a native Java solution without needing JNI/JNA, though note that Windows-specific tag names aren't explicitly supported yet (as of Java 21)—the shared session uses OS-specific identifiers under the hood, but you can't directly specify a user-friendly tag name like with the Windows API.
Can you specify a tag name for anonymous mappings on Windows?
Yes—but only if you use the Windows Native API approach (Option 2 above). As shown in the example, the lpName parameter in CreateFileMappingW lets you set a unique tag name that other processes can use to connect to the same anonymous memory segment. This works exactly like Python's approach with mmap and a tag name.
内容的提问来源于stack exchange,提问作者FThompson

