From 8c9ef95beab5ffc0ff5763e1db308f5983e1c906 Mon Sep 17 00:00:00 2001 From: Jason Simmons Date: Mon, 30 Apr 2018 10:44:01 -0700 Subject: [PATCH] Detach from JNI during shutdown of the UI thread on Android (flutter/engine#5120) The APKAssetProvider will hold a reference to its Java peer (see https://github.com/flutter/engine/commit/c2b081e229eb3c1103d0d06f0c9d7057166ece1d) After dropping this reference, the UI thread must detach from JNI before exiting. --- .../platform/android/android_shell_holder.cc | 20 ++++++++++++++++++- .../platform/android/android_shell_holder.h | 3 +++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/engine/src/flutter/shell/platform/android/android_shell_holder.cc b/engine/src/flutter/shell/platform/android/android_shell_holder.cc index 7dc454f1fb..5ef505e77a 100644 --- a/engine/src/flutter/shell/platform/android/android_shell_holder.cc +++ b/engine/src/flutter/shell/platform/android/android_shell_holder.cc @@ -6,6 +6,7 @@ #include "flutter/shell/platform/android/android_shell_holder.h" +#include #include #include @@ -27,9 +28,18 @@ AndroidShellHolder::AndroidShellHolder( static size_t shell_count = 1; auto thread_label = std::to_string(shell_count++); + FXL_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) == + 0); + thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU | ThreadHost::Type::IO}; + // Detach from JNI when the UI thread exits. + thread_host_.ui_thread->GetTaskRunner()->PostTask( + [key = thread_destruct_key_]() { + FXL_CHECK(pthread_setspecific(key, reinterpret_cast(1)) == 0); + }); + fml::WeakPtr weak_platform_view; Shell::CreateCallback on_create_platform_view = [java_object, &weak_platform_view](Shell& shell) { @@ -80,7 +90,15 @@ AndroidShellHolder::AndroidShellHolder( } } -AndroidShellHolder::~AndroidShellHolder() = default; +AndroidShellHolder::~AndroidShellHolder() { + shell_.reset(); + thread_host_.Reset(); + FXL_CHECK(pthread_key_delete(thread_destruct_key_) == 0); +} + +void AndroidShellHolder::ThreadDestructCallback(void* value) { + fml::jni::DetachFromVM(); +} bool AndroidShellHolder::IsValid() const { return is_valid_; diff --git a/engine/src/flutter/shell/platform/android/android_shell_holder.h b/engine/src/flutter/shell/platform/android/android_shell_holder.h index e0905f0f9e..4bf42a776d 100644 --- a/engine/src/flutter/shell/platform/android/android_shell_holder.h +++ b/engine/src/flutter/shell/platform/android/android_shell_holder.h @@ -50,6 +50,9 @@ class AndroidShellHolder { ThreadHost thread_host_; std::unique_ptr shell_; bool is_valid_ = false; + pthread_key_t thread_destruct_key_; + + static void ThreadDestructCallback(void* value); FXL_DISALLOW_COPY_AND_ASSIGN(AndroidShellHolder); };