This is an automated email from the ASF dual-hosted git repository.
philo-he pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gluten.git
The following commit(s) were added to refs/heads/main by this push:
new 84ac7cb66e [GLUTEN-13729][VL] Detach Gluten-attached native threads
from the JVM when they exit (#13728)
84ac7cb66e is described below
commit 84ac7cb66e3e19b4956cede5964c41922a130d86
Author: Philo He <[email protected]>
AuthorDate: Wed Nov 25 06:38:15 2026 +0800
[GLUTEN-13729][VL] Detach Gluten-attached native threads from the JVM when
they exit (#13728)
---
cpp/core/CMakeLists.txt | 1 +
cpp/core/jni/JniCommon.h | 6 ++
cpp/core/jni/JniThreadExit.cc | 93 ++++++++++++++++++++++
cpp/core/jni/JniThreadExit.h | 36 +++++++++
cpp/core/tests/CMakeLists.txt | 1 +
cpp/core/tests/JniThreadExitTest.cc | 155 ++++++++++++++++++++++++++++++++++++
6 files changed, 292 insertions(+)
diff --git a/cpp/core/CMakeLists.txt b/cpp/core/CMakeLists.txt
index 6033bc3848..cf6227bc50 100644
--- a/cpp/core/CMakeLists.txt
+++ b/cpp/core/CMakeLists.txt
@@ -149,6 +149,7 @@ set(SPARK_COLUMNAR_PLUGIN_SRCS
jni/JavaException.cc
jni/JniError.cc
jni/JniCommon.cc
+ jni/JniThreadExit.cc
jni/TaskContextJniWrapper.cc)
file(MAKE_DIRECTORY ${root_directory}/releases)
diff --git a/cpp/core/jni/JniCommon.h b/cpp/core/jni/JniCommon.h
index b72fd3eee9..e398367c2c 100644
--- a/cpp/core/jni/JniCommon.h
+++ b/cpp/core/jni/JniCommon.h
@@ -27,6 +27,7 @@
#include "JavaException.h"
#include "compute/ProtobufUtils.h"
#include "compute/Runtime.h"
+#include "jni/JniThreadExit.h"
#include "memory/AllocationListener.h"
#include "shuffle/ShuffleReader.h"
#include "shuffle/rss/RssClient.h"
@@ -114,6 +115,11 @@ static inline void
attachCurrentThreadAsDaemonOrThrow(JavaVM* vm, JNIEnv** out)
if (getEnvStat != JNI_OK) {
throw gluten::GlutenException("Failed to reattach current thread to
JVM.");
}
+ // Detach when this native thread exits, so the JVM is not left with a
JavaThread for a dead pthread.
+ // Only threads attached here are registered: Java-created threads, and
native threads that Java
+ // or libhdfs attached first, never return JNI_EDETACHED above, so the JVM
and libhdfs keep
+ // managing their detach.
+ gluten::detachCurrentThreadOnExit(vm);
DLOG(INFO) << "Succeeded attaching current thread.";
return;
}
diff --git a/cpp/core/jni/JniThreadExit.cc b/cpp/core/jni/JniThreadExit.cc
new file mode 100644
index 0000000000..3121aa58a3
--- /dev/null
+++ b/cpp/core/jni/JniThreadExit.cc
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "jni/JniThreadExit.h"
+
+#include <pthread.h>
+
+#include <atomic>
+#include <cstdint>
+
+#include <glog/logging.h>
+
+namespace gluten {
+namespace {
+
+// The TSD value of a thread whose detach is pending. A destructor that finds
kArmed has run in the
+// first destructor round; it re-arms with kDeferred so that it is called
again in the next round.
+constexpr uintptr_t kArmed = 1;
+constexpr uintptr_t kDeferred = 2;
+
+// The VM to detach from. The destructor only receives the TSD value (kArmed
or kDeferred), so it reads
+// the VM from here. Every registration stores the same pointer, since a
process has one JVM; the
+// atomic only avoids a data race between registering threads and exiting
threads.
+std::atomic<JavaVM*> exitDetachVm{nullptr};
+pthread_key_t exitDetachKey;
+
+// Why the detach waits one destructor round:
+//
+// libhdfs caches the JNIEnv* of each thread it uses and detaches that thread
from its own TSD
+// destructor, which still dereferences the cached JNIEnv*. If this destructor
detached first, libhdfs
+// would use a freed JNIEnv* (the crash fixed by GLUTEN-11895, which is why
Gluten stopped detaching
+// in its JNI helpers). POSIX re-runs TSD destructors for keys whose values
are non-NULL again after a
+// round, and glibc does so for up to PTHREAD_DESTRUCTOR_ITERATIONS (4)
rounds. Deferring by one round
+// means libhdfs's destructor has run, whatever its key's position, before
this one acts: the thread
+// is then already detached (GetEnv returns JNI_EDETACHED and nothing is done)
or libhdfs never owned
+// it and this destructor detaches it.
+//
+// Detaching from a TSD destructor is supported by HotSpot: its own TSD
destructor restores the
+// current-thread pointer so that later destructors can still call
DetachCurrentThread.
+//
+// A C++ thread_local destructor cannot replace this key: glibc runs all
thread_local destructors
+// before any pthread TSD destructor, so the detach would always precede
libhdfs's destructor and
+// bring back the GLUTEN-11895 crash for threads that libhdfs uses.
+void detachOnThreadExit(void* value) {
+ if (reinterpret_cast<uintptr_t>(value) == kArmed) {
+ pthread_setspecific(exitDetachKey, reinterpret_cast<void*>(kDeferred));
+ return;
+ }
+ JavaVM* vm = exitDetachVm.load(std::memory_order_acquire);
+ JNIEnv* env = nullptr;
+ // JNI_VERSION_1_8 is the JNI interface version requested from GetEnv, the
same one Gluten uses
+ // everywhere; every JDK from 8 on supports it, so this check applies to all
JDKs. It only asks
+ // whether the thread is still attached: JNI_EDETACHED means libhdfs already
detached it.
+ if (vm != nullptr && vm->GetEnv(reinterpret_cast<void**>(&env),
JNI_VERSION_1_8) == JNI_OK) {
+ vm->DetachCurrentThread();
+ }
+}
+
+bool createExitDetachKey() {
+ const int rc = pthread_key_create(&exitDetachKey, detachOnThreadExit);
+ if (rc != 0) {
+ LOG(WARNING) << "pthread_key_create failed with " << rc
+ << "; native threads will stay attached to the JVM after they
exit";
+ }
+ return rc == 0;
+}
+
+} // namespace
+
+void detachCurrentThreadOnExit(JavaVM* vm) {
+ static const bool keyCreated = createExitDetachKey();
+ if (!keyCreated) {
+ return;
+ }
+ exitDetachVm.store(vm, std::memory_order_release);
+ pthread_setspecific(exitDetachKey, reinterpret_cast<void*>(kArmed));
+}
+
+} // namespace gluten
diff --git a/cpp/core/jni/JniThreadExit.h b/cpp/core/jni/JniThreadExit.h
new file mode 100644
index 0000000000..d15eb295b0
--- /dev/null
+++ b/cpp/core/jni/JniThreadExit.h
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <jni.h>
+
+namespace gluten {
+
+/// Arranges for the calling native thread to be detached from `vm` when the
thread exits.
+///
+/// Call this right after Gluten attaches a native thread to the JVM. A native
thread that exits while
+/// still attached leaves a JavaThread whose pthread no longer exists; the
next walk of the JVM thread
+/// list (thread dump, jcmd, JVMTI agents, profilers, EMR log collection) then
reads that dead pthread
+/// and crashes in pthread_getcpuclockid. Native pool threads do exit while
the executor runs, since
+/// folly pools retire idle workers after --threadtimeout_ms.
+///
+/// The detach runs from a pthread TSD destructor and is safe for threads that
libhdfs also uses; see
+/// JniThreadExit.cc. Calling it more than once on a thread is harmless.
+void detachCurrentThreadOnExit(JavaVM* vm);
+
+} // namespace gluten
diff --git a/cpp/core/tests/CMakeLists.txt b/cpp/core/tests/CMakeLists.txt
index 26ae2bc47d..60f538e703 100644
--- a/cpp/core/tests/CMakeLists.txt
+++ b/cpp/core/tests/CMakeLists.txt
@@ -20,5 +20,6 @@ add_test_case(ffor_codec_test SOURCES FForCodecTest.cc)
add_test_case(print_config_test SOURCES PrintConfigTest.cc)
add_test_case(payload_test SOURCES PayloadTest.cc)
add_test_case(java_exception_test SOURCES JavaExceptionTest.cc)
+add_test_case(jni_thread_exit_test SOURCES JniThreadExitTest.cc)
add_test_case(java_exception_allocation_test SOURCES
JavaExceptionAllocationTest.cc)
diff --git a/cpp/core/tests/JniThreadExitTest.cc
b/cpp/core/tests/JniThreadExitTest.cc
new file mode 100644
index 0000000000..1e150d4591
--- /dev/null
+++ b/cpp/core/tests/JniThreadExitTest.cc
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include <pthread.h>
+
+#include <cstdlib>
+#include <thread>
+
+#include "jni/JniCommon.h"
+#include "tests/utils/TestJniEnvironment.h"
+
+using namespace gluten;
+
+namespace {
+
+JavaVM* vmOf(TestJniEnvironment& jni) {
+ JavaVM* vm = nullptr;
+ jni.env()->GetJavaVM(&vm);
+ return vm;
+}
+
+void glutenAttach(JavaVM* vm) {
+ JNIEnv* env = nullptr;
+ attachCurrentThreadAsDaemonOrThrow(vm, &env);
+ ASSERT_NE(env, nullptr);
+}
+
+// Mirrors libhdfs: it caches the thread's JNIEnv* in a pthread key and, from
that key's destructor
+// at thread exit, still uses the JNIEnv* and then detaches the thread
(hdfsThreadDestructor).
+struct HdfsLikeState {
+ TestJniEnvironment* jni{nullptr};
+ bool attachedWhenDestructorRan{false};
+};
+
+void hdfsLikeDestructor(void* value) {
+ auto* state = static_cast<HdfsLikeState*>(value);
+ state->attachedWhenDestructorRan = state->jni->workerAttached;
+ vmOf(*state->jni)->DetachCurrentThread();
+}
+
+// Also called during static initialization, where gtest assertions must not
be used, so abort on failure.
+pthread_key_t createHdfsLikeKey() {
+ pthread_key_t key;
+ if (pthread_key_create(&key, hdfsLikeDestructor) != 0) {
+ std::abort();
+ }
+ return key;
+}
+
+// Created during static initialization, so before Gluten's key: its
destructor runs first in each round.
+const pthread_key_t hdfsKeyCreatedBeforeGluten = createHdfsLikeKey();
+
+void runHdfsAfterGlutenAttach(pthread_key_t hdfsKey) {
+ TestJniEnvironment jni;
+ HdfsLikeState state{&jni};
+ std::thread worker([&] {
+ glutenAttach(vmOf(jni));
+ pthread_setspecific(hdfsKey, &state); // libhdfs then uses the
already-attached thread.
+ });
+ worker.join();
+ EXPECT_TRUE(state.attachedWhenDestructorRan); // libhdfs never sees a
detached thread.
+ EXPECT_EQ(jni.attaches, 1);
+ EXPECT_EQ(jni.detaches, 1); // only libhdfs detached it.
+ EXPECT_FALSE(jni.workerAttached);
+}
+
+} // namespace
+
+TEST(JniThreadExitTest, detachesThreadAttachedByGlutenOnExit) {
+ TestJniEnvironment jni;
+ std::thread worker([&] { glutenAttach(vmOf(jni)); });
+ worker.join();
+ EXPECT_EQ(jni.attaches, 1);
+ EXPECT_EQ(jni.detaches, 1);
+ EXPECT_FALSE(jni.workerAttached);
+}
+
+TEST(JniThreadExitTest, doesNotDetachThreadAttachedElsewhere) {
+ TestJniEnvironment jni;
+ jni.workerAttached = true; // e.g. a Java-created thread, or one Java or
libhdfs attached first.
+ std::thread worker([&] { glutenAttach(vmOf(jni)); });
+ worker.join();
+ EXPECT_EQ(jni.attaches, 0);
+ EXPECT_EQ(jni.detaches, 0);
+ EXPECT_TRUE(jni.workerAttached);
+}
+
+TEST(JniThreadExitTest, detachesOnceWhenHelperIsCalledRepeatedly) {
+ TestJniEnvironment jni;
+ std::thread worker([&] {
+ for (int i = 0; i < 3; ++i) {
+ glutenAttach(vmOf(jni));
+ }
+ });
+ worker.join();
+ EXPECT_EQ(jni.attaches, 1);
+ EXPECT_EQ(jni.detaches, 1);
+}
+
+TEST(JniThreadExitTest, detachesReattachedThreadOnExit) {
+ TestJniEnvironment jni;
+ std::thread worker([&] {
+ glutenAttach(vmOf(jni));
+ vmOf(jni)->DetachCurrentThread();
+ glutenAttach(vmOf(jni));
+ });
+ worker.join();
+ EXPECT_EQ(jni.attaches, 2);
+ EXPECT_EQ(jni.detaches, 2); // one explicit detach, one at thread exit.
+ EXPECT_FALSE(jni.workerAttached);
+}
+
+TEST(JniThreadExitTest, libhdfsDestructorRunsFirstWhenItsKeyIsOlder) {
+ runHdfsAfterGlutenAttach(hdfsKeyCreatedBeforeGluten);
+}
+
+TEST(JniThreadExitTest, libhdfsDestructorRunsFirstWhenItsKeyIsNewer) {
+ {
+ // Make sure Gluten's key exists before creating the libhdfs-like key.
+ TestJniEnvironment jni;
+ std::thread worker([&] { glutenAttach(vmOf(jni)); });
+ worker.join();
+ }
+ runHdfsAfterGlutenAttach(createHdfsLikeKey());
+}
+
+TEST(JniThreadExitTest, leavesThreadAttachedByLibhdfsToLibhdfs) {
+ TestJniEnvironment jni;
+ HdfsLikeState state{&jni};
+ std::thread worker([&] {
+ JNIEnv* env = nullptr;
+ vmOf(jni)->AttachCurrentThreadAsDaemon(reinterpret_cast<void**>(&env),
nullptr); // libhdfs attaches.
+ pthread_setspecific(hdfsKeyCreatedBeforeGluten, &state);
+ glutenAttach(vmOf(jni)); // Gluten then uses it; already attached, so
nothing is registered.
+ });
+ worker.join();
+ EXPECT_TRUE(state.attachedWhenDestructorRan);
+ EXPECT_EQ(jni.attaches, 1);
+ EXPECT_EQ(jni.detaches, 1);
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]