Skip to content

Commit 38bcbb4

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.
1 parent 8ce8ddc commit 38bcbb4

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (C) 2019 HERE Europe B.V.
2+
* Copyright (C) 2019-2026 HERE Europe B.V.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@
2222
#ifdef __ANDROID__
2323

2424
#include <jni.h>
25+
#include <pthread.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+
getThreadName();
40+
auto attachArgs = getJvmAttachArgs();
41+
if (jni_vm_->AttachCurrentThread(&jni_env_, &attachArgs) == JNI_OK) {
3942
attached_ = true;
4043
}
4144
}
@@ -56,9 +59,20 @@ class JNIThreadBinder final {
5659
JNIEnv* GetEnv() const { return jni_env_; }
5760

5861
private:
62+
void getThreadName() {
63+
pthread_getname_np(pthread_self(), threadName_, sizeof(threadName_));
64+
}
65+
66+
JavaVMAttachArgs getJvmAttachArgs() const {
67+
return JavaVMAttachArgs{.version = JNI_VERSION_1_6,
68+
.name = threadName_[0] ? threadName_ : nullptr,
69+
.group = nullptr};
70+
}
71+
5972
bool attached_;
6073
JNIEnv* jni_env_;
6174
JavaVM* jni_vm_;
75+
char threadName_[16] = {0};
6276
};
6377

6478
} // namespace utils

0 commit comments

Comments
 (0)