Skip to content

Commit

Permalink
apacheGH-20379: [Java] Dataset Failed to update reservation while fre…
Browse files Browse the repository at this point in the history
…eing bytes: JNIEnv was not attached to current thread
  • Loading branch information
fb64 committed Feb 16, 2024
1 parent a03d957 commit 9aab65c
Showing 1 changed file with 38 additions and 8 deletions.
46 changes: 38 additions & 8 deletions java/dataset/src/main/cpp/jni_wrapper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,40 @@ void ThrowIfError(const arrow::Status& status) {
}
}

class JNIEnvGuard {
public:
explicit JNIEnvGuard(JavaVM* vm) : vm_(vm), should_detach_(false) {
JNIEnv* env;
jint code = vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION);
if (code == JNI_EDETACHED) {
JavaVMAttachArgs args;
args.version = JNI_VERSION;
args.name = NULL;
args.group = NULL;
code = vm->AttachCurrentThread(reinterpret_cast<void**>(&env), &args);
should_detach_ = (code == JNI_OK);
}
if (code != JNI_OK) {
ThrowPendingException("Failed to attach the current thread to a Java VM");
}
env_ = env;
}

JNIEnv* env() { return env_; }

~JNIEnvGuard() {
if (should_detach_) {
vm_->DetachCurrentThread();
should_detach_ = false;
}
}

private:
bool should_detach_;
JavaVM* vm_;
JNIEnv* env_;
};

template <typename T>
T JniGetOrThrow(arrow::Result<T> result) {
const arrow::Status& status = result.status();
Expand Down Expand Up @@ -126,20 +160,16 @@ class ReserveFromJava : public arrow::dataset::jni::ReservationListener {
: vm_(vm), java_reservation_listener_(java_reservation_listener) {}

arrow::Status OnReservation(int64_t size) override {
JNIEnv* env;
if (vm_->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION) != JNI_OK) {
return arrow::Status::Invalid("JNIEnv was not attached to current thread");
}
JNIEnvGuard guard(vm_);
JNIEnv* env = guard.env();
env->CallObjectMethod(java_reservation_listener_, reserve_memory_method, size);
RETURN_NOT_OK(arrow::dataset::jni::CheckException(env));
return arrow::Status::OK();
}

arrow::Status OnRelease(int64_t size) override {
JNIEnv* env;
if (vm_->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION) != JNI_OK) {
return arrow::Status::Invalid("JNIEnv was not attached to current thread");
}
JNIEnvGuard guard(vm_);
JNIEnv* env = guard.env();
env->CallObjectMethod(java_reservation_listener_, unreserve_memory_method, size);
RETURN_NOT_OK(arrow::dataset::jni::CheckException(env));
return arrow::Status::OK();
Expand Down

0 comments on commit 9aab65c

Please sign in to comment.