Luke
Luke

Reputation: 344

How can you use a mutex between c# and java processes?

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

Answers (1)

Gamlor
Gamlor

Reputation: 13248

There are multiple options:

  • Using a file based lock, as you mentioned
  • Using a memory mapped file, and a protocol based on low level memory access. This is hard to get right, and you need access 'sun.misc.Unsafe' operations. I would look into libraries like OpenHFT, which gives you reasonable API over the unsafe operation. However, it is still hard.
  • Use JNI to use the Win32 / unix API's for inter process locks. I recommend to use something like JNA or JNR, which allows you to call C apis without writing the JNI C part.

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

Related Questions