Skip to content

Commit 515264f

Browse files
Keep thread name after attaching it to JVM
When native thread is attached to JVM, then it's name is taken from JavaVMAttachArgs. When no JavaVMAttachArgs, or no JavaVMAttachArgs::name passed, then JVM on its own decides on naming thread. Those names are not descriptive. To preserve thread name, pass the currently set thread name in JavaVMAttachArgs::name. Relates-To: HNAV-15387 Signed-off-by: Michal Zimonczyk <ext-michal.zimonczyk@here.com>
1 parent 8ce8ddc commit 515264f

1 file changed

Lines changed: 18 additions & 1 deletion

File tree

olp-cpp-sdk-core/src/http/android/utils/JNIThreadBinder.h

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#ifdef __ANDROID__
2323

2424
#include <jni.h>
25+
#include <sys/prctl.h>
2526

2627
namespace olp {
2728
namespace http {
@@ -35,7 +36,9 @@ class JNIThreadBinder final {
3536
: attached_(false), jni_env_(nullptr), jni_vm_(vm) {
3637
if (jni_vm_->GetEnv(reinterpret_cast<void**>(&jni_env_), JNI_VERSION_1_6) !=
3738
JNI_OK) {
38-
if (jni_vm_->AttachCurrentThread(&jni_env_, nullptr) == JNI_OK) {
39+
captureThreadName();
40+
auto attachArgs = getJvmAttachArgs();
41+
if (jni_vm_->AttachCurrentThread(&jni_env_, &attachArgs) == JNI_OK) {
3942
attached_ = true;
4043
}
4144
}
@@ -56,9 +59,23 @@ class JNIThreadBinder final {
5659
JNIEnv* GetEnv() const { return jni_env_; }
5760

5861
private:
62+
void captureThreadName() {
63+
if (prctl(PR_GET_NAME, threadName_) != 0) {
64+
threadName_[0] = '\0';
65+
}
66+
}
67+
68+
JavaVMAttachArgs getJvmAttachArgs() const {
69+
return JavaVMAttachArgs{.version = JNI_VERSION_1_6,
70+
.name = threadName_[0] ? threadName_ : nullptr,
71+
.group = nullptr};
72+
}
73+
5974
bool attached_;
6075
JNIEnv* jni_env_;
6176
JavaVM* jni_vm_;
77+
constexpr static size_t kThreadNameMaxLength = 16;
78+
char threadName_[kThreadNameMaxLength] = {0};
6279
};
6380

6481
} // namespace utils

0 commit comments

Comments
 (0)