Skip to content

Commit

Permalink
Merge pull request #133 from jamesjer/master
Browse files Browse the repository at this point in the history
Avoid jacop-related crashes due to destructor execution order
  • Loading branch information
glebbelov authored May 7, 2021
2 parents 7030ef3 + 08aa7ba commit 232709d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
22 changes: 17 additions & 5 deletions solvers/jacop/java.cc
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ std::string RegKey::GetStrValue(fmt::CStringRef name) const {

namespace mp {

JVM JVM::instance_;
JVM *JVM::instance_;

void Env::Throw(jthrowable exception, const char *method_name) {
env_->ExceptionClear();
Expand Down Expand Up @@ -190,8 +190,16 @@ JVM::~JVM() {
jvm_->DestroyJavaVM();
}

void JVM::cleanup_jvm()
{
if (instance_) {
delete instance_;
instance_ = nullptr;
}
}

Env JVM::env(const char *const *options) {
if (!instance_.jvm_) {
if (!instance_) {
#ifdef _WIN32
std::string runtime_lib_path;
bool exists = false;
Expand Down Expand Up @@ -251,15 +259,19 @@ Env JVM::env(const char *const *options) {
}
vm_args.nOptions = static_cast<jint>(jvm_options.size());
vm_args.options = &jvm_options[0];
instance_ = new JVM();
void *envp = 0;
jint result = JNI_CreateJavaVM(&instance_.jvm_, &envp, &vm_args);
jint result = JNI_CreateJavaVM(&instance_->jvm_, &envp, &vm_args);
if (result != JNI_OK) {
delete instance_;
instance_ = nullptr;
throw JavaError(fmt::format(
"Java VM initialization failed, error code = {}", result));
}
instance_.env_ = Env(static_cast<JNIEnv*>(envp));
instance_->env_ = Env(static_cast<JNIEnv*>(envp));
std::atexit(cleanup_jvm);
}
return instance_.env_;
return instance_->env_;
}

ClassBase::~ClassBase() {}
Expand Down
3 changes: 2 additions & 1 deletion solvers/jacop/java.h
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,8 @@ class JVM {
private:
JavaVM *jvm_;
Env env_;
static JVM instance_;
static JVM *instance_;
static void cleanup_jvm();

JVM() : jvm_() {}
~JVM();
Expand Down

0 comments on commit 232709d

Please sign in to comment.