0
\$\begingroup\$

I have this JNI code to review. The demo driver + irrelevant porting code is here.

semaphore_impl.h:

#ifndef WINDOWS_SEMAPHORE_IMPL_H
#define WINDOWS_SEMAPHORE_IMPL_H
#include <jni.h>

#ifdef __cplusplus
extern "C" {
#endif

    JNIEXPORT void JNICALL
        Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_init(
            JNIEnv*,
            jobject,
            jint,
            jint);

    JNIEXPORT void JNICALL
        Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_clean(JNIEnv*, jobject);

    JNIEXPORT void JNICALL
        Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_lock(JNIEnv*, jobject);

    JNIEXPORT void JNICALL
        Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_unlock(JNIEnv*, jobject);

#ifdef __cplusplus
}
#endif

#endif // WINDOWS_SEMAPHORE_IMPL_H

semaphore_impl.cpp:

#include "semaphore_impl.h"
#include <windows.h>

static const char* CLASS = "net/coderodde/util/concurrent/WindowsSemaphoreImpl";
static const char* FIELD = "semaphoreHandle";

static HANDLE get_semaphore_handle(JNIEnv* env, jobject obj)
{
    jclass clazz = env->FindClass(CLASS);
    jfieldID fid = env->GetFieldID(clazz, FIELD, "J");
    return (HANDLE) env->GetLongField(obj, fid); 
}

JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_init(
    JNIEnv* env,
    jobject obj,
    jint maxCount,
    jint count)
{
    // Create a handle to a semaphore.
    HANDLE semaphore;
    semaphore = CreateSemaphore(NULL,
                                count,
                                maxCount,
                                NULL);

    // Get to the 'semaphoreHandle' field.
    const jclass clazz = env->FindClass(CLASS);
    const jfieldID semaphore_field_id = env->GetFieldID(clazz, FIELD, "J");

    // Store the value of the semaphore to the Java semaphore object.
    env->SetLongField(obj, semaphore_field_id, (jlong) semaphore);
}

JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_clean(
    JNIEnv* env,
    jobject obj)
{
    CloseHandle(get_semaphore_handle(env, obj));
}

JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_lock(
    JNIEnv* env,
    jobject obj)
{
    WaitForSingleObject(get_semaphore_handle(env, obj), INFINITE);
}

JNIEXPORT void JNICALL
Java_net_coderodde_util_concurrent_WindowsSemaphoreImpl_unlock(
    JNIEnv* env,
    jobject obj)
{
    ReleaseSemaphore(get_semaphore_handle(env, obj), 1L, NULL);
}
\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.