Skip to content

Commit

Permalink
issue #1 release local references to allocated arrays so that the JVM…
Browse files Browse the repository at this point in the history
… can reclaim memory sooner
  • Loading branch information
Dibyendu Majumdar committed Aug 22, 2017
1 parent 1a92c9c commit 47db88e
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/main/cpp/nlopt_jni.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ extern "C" {
}

if (data->func) {
jdoubleArray xarray;
jdoubleArray gradientarray;
jdoubleArray xarray = NULL;
jdoubleArray gradientarray = NULL;

// Create Java arrays
xarray = jni->NewDoubleArray(n);
Expand All @@ -76,6 +76,8 @@ extern "C" {
unsigned gsize = gradient ? n : 0;
gradientarray = jni->NewDoubleArray(gsize);
if (!gradientarray || jni->ExceptionCheck()) {
// avoid holding on to memory - see issue #1
jni->DeleteLocalRef(xarray);
nlopt_force_stop(data->handle);
return 0.0; // ignored
}
Expand All @@ -87,6 +89,9 @@ extern "C" {
// Call Java function
jdouble result = jni->CallDoubleMethod(data->func, nlopt_func_execute_method, xarray, gradientarray);
if (jni->ExceptionCheck()) {
// avoid holding on to memory - see issue #1
jni->DeleteLocalRef(xarray);
jni->DeleteLocalRef(gradientarray);
nlopt_force_stop(data->handle);
return 0.0; // ignored
}
Expand All @@ -95,6 +100,9 @@ extern "C" {
jboolean is_copy = false;
double *xcopy = jni->GetDoubleArrayElements(gradientarray, &is_copy);
if (!xcopy || jni->ExceptionCheck()) {
// avoid holding on to memory - see issue #1
jni->DeleteLocalRef(xarray);
jni->DeleteLocalRef(gradientarray);
nlopt_force_stop(data->handle);
return 0.0; // ignored
}
Expand All @@ -103,6 +111,9 @@ extern "C" {
// Release the managed copy
jni->ReleaseDoubleArrayElements(gradientarray, xcopy, 0);
}
// avoid holding on to memory - see issue #1
jni->DeleteLocalRef(xarray);
jni->DeleteLocalRef(gradientarray);
return result;
}
jni->ThrowNew(illegal_argument_exception_class, "No function set");
Expand Down

0 comments on commit 47db88e

Please sign in to comment.