Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JVM crashes on Windows when using JNI to call a C++ dll using a mutex #510

Closed
aaron-bray opened this issue Jul 3, 2024 · 1 comment
Closed
Labels
bug Something isn't working

Comments

@aaron-bray
Copy link

I have created a windows dll with a main.cpp containing only the following function, loaded the dll in Java 8
to call said native function, and it blows up in the lock method if I use the dynamic runtime /MD but runs fine if built with the /MT

This worked in jdk1.8.0_372, but now fails in jdk1.8.0_412

hs_err_pid21540.log

#include <jni.h>
#include <iostream>
#include <mutex>

extern "C"
JNIEXPORT jboolean JNICALL Java_com_kitware_MutexTest_nativeMutex(JNIEnv* env, jobject obj)
{
  std::cout << "Hello" << std::endl;
  std::mutex mtx;
  mtx.lock();
  std::cout << "World" << std::endl;
  return true;
}

Using this as my CMakeLists.txt do build the dll

cmake_minimum_required(VERSION 3.26)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_EXTENSIONS False)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)


project(JNIMutex LANGUAGES C CXX)

find_package(Java REQUIRED)
if(Java_FOUND)
  include(UseJava)
  find_package(JNI REQUIRED)
  if(Java_JAVA_EXECUTABLE)
    message(STATUS "Using Java executable : ${Java_JAVA_EXECUTABLE}")
    set(Java_CMD ${Java_JAVA_EXECUTABLE})
  else()
    message(STATUS "Could not find Java_JAVA_EXECUTABLE")
  endif()
endif()

# Uncommented == /MT (OK!), Commented == /MD (Crash)
#set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")

add_library(mutex SHARED main.cpp)
message(STATUS "JNI_INCLUDE_DIRS : ${JNI_INCLUDE_DIRS}")
target_include_directories(mutex PRIVATE ${JNI_INCLUDE_DIRS})

Java file calling this native method:

package com.kitware;

public class MutexTest
{
  public static void main(String[] args)
  {
    try
    {
      System.loadLibrary("mutex");
      MutexTest mt = new MutexTest();
      mt.nativeMutex();
    }
    catch(Exception ex)
    {
      System.out.println("Error: "+ex);
    }
  }
  public native boolean nativeMutex();
}
@aaron-bray
Copy link
Author

It looks like this problems goes all the way up to MSVC

https://stackoverflow.com/questions/78598141/first-stdmutexlock-crashes-in-application-built-with-latest-visual-studio

This solution works and will keep any eye on MSVC for more about this issue

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant