jni_weak_ref.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_ANDROID_JNI_WEAK_REF_H_
  5. #define BASE_ANDROID_JNI_WEAK_REF_H_
  6. #include <jni.h>
  7. #include "base/android/scoped_java_ref.h"
  8. #include "base/base_export.h"
  9. // Manages WeakGlobalRef lifecycle.
  10. // This class is not thread-safe w.r.t. get() and reset(). Multiple threads may
  11. // safely use get() concurrently, but if the user calls reset() (or of course,
  12. // calls the destructor) they'll need to provide their own synchronization.
  13. class BASE_EXPORT JavaObjectWeakGlobalRef {
  14. public:
  15. JavaObjectWeakGlobalRef();
  16. JavaObjectWeakGlobalRef(const JavaObjectWeakGlobalRef& orig);
  17. JavaObjectWeakGlobalRef(JavaObjectWeakGlobalRef&& orig) noexcept;
  18. JavaObjectWeakGlobalRef(JNIEnv* env, jobject obj);
  19. JavaObjectWeakGlobalRef(JNIEnv* env,
  20. const base::android::JavaRef<jobject>& obj);
  21. virtual ~JavaObjectWeakGlobalRef();
  22. void operator=(const JavaObjectWeakGlobalRef& rhs);
  23. void operator=(JavaObjectWeakGlobalRef&& rhs);
  24. base::android::ScopedJavaLocalRef<jobject> get(JNIEnv* env) const;
  25. // Returns true if the weak reference has not been initialized to point at
  26. // an object (or ḣas had reset() called).
  27. // Do not call this to test if the object referred to still exists! The weak
  28. // reference remains initialized even if the target object has been collected.
  29. bool is_uninitialized() const { return obj_ == nullptr; }
  30. void reset();
  31. private:
  32. void Assign(const JavaObjectWeakGlobalRef& rhs);
  33. jweak obj_;
  34. };
  35. // Get the real object stored in the weak reference returned as a
  36. // ScopedJavaLocalRef.
  37. BASE_EXPORT base::android::ScopedJavaLocalRef<jobject> GetRealObject(
  38. JNIEnv* env, jweak obj);
  39. #endif // BASE_ANDROID_JNI_WEAK_REF_H_