Reputation: 344
I would like to do a consumer-producer pattern using memory mapped files from java to c#. I need a low latency way of signalling from java to c# to read the data.
In c# you can use a named Mutex (new Mutex(true,"sharedMutex1")) between processes and use Mutex.WaitOne() and Mutex.ReleaseMutex() to control between processes.
How can I do this from a Java process?
edit: I am aware you can use a File Lock to do it but I would like to keep away from the file system to keep latency low.
edit: another option is to use c++ via JNI. So I guess I am asking now if it can be done in Java directly?
Upvotes: 3
Views: 1126
Reputation: 13248
There are multiple options:
Here a example with JNA which calls into the WIN32 lock API:
/**
* Definitions of the Win32 API. JNA has some for windows, so check first
* In case CreateMutex is not included.
*/
public interface Kernel32Ex extends Kernel32 {
WinNT.HANDLE CreateMutex(
WinBase.SECURITY_ATTRIBUTES lpMutexAttributes,
boolean bInitialOwner,
String lpName
);
boolean ReleaseMutex(
WinNT.HANDLE hMutex
);
}
public static void main(String[] args) throws Exception {
// The binding. Create it once
final Kernel32Ex Win32 = Native.loadLibrary("kernel32", Kernel32Ex.class, W32APIOptions.UNICODE_OPTIONS);
WinNT.HANDLE handle = Win32.CreateMutex(null,
true,
"My-Mutext");
if (handle == null) {
throw new Win32Exception(Win32.GetLastError());
} else {
System.out.println("Holding the win32 mutex");
Win32.ReleaseMutex(handle);
}
}
Upvotes: 6