jnicallback.cc 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // This file implements the callback "bridge" between Java and C++ for
  7. // JNI Callbacks from C++ to sub-classes or org.rocksdb.RocksCallbackObject
  8. #include <assert.h>
  9. #include "rocksjni/jnicallback.h"
  10. #include "rocksjni/portal.h"
  11. namespace ROCKSDB_NAMESPACE {
  12. JniCallback::JniCallback(JNIEnv* env, jobject jcallback_obj) {
  13. // Note: jcallback_obj may be accessed by multiple threads,
  14. // so we ref the jvm not the env
  15. const jint rs = env->GetJavaVM(&m_jvm);
  16. if(rs != JNI_OK) {
  17. // exception thrown
  18. return;
  19. }
  20. // Note: we may want to access the Java callback object instance
  21. // across multiple method calls, so we create a global ref
  22. assert(jcallback_obj != nullptr);
  23. m_jcallback_obj = env->NewGlobalRef(jcallback_obj);
  24. if(jcallback_obj == nullptr) {
  25. // exception thrown: OutOfMemoryError
  26. return;
  27. }
  28. }
  29. JNIEnv* JniCallback::getJniEnv(jboolean* attached) const {
  30. return JniUtil::getJniEnv(m_jvm, attached);
  31. }
  32. void JniCallback::releaseJniEnv(jboolean& attached) const {
  33. JniUtil::releaseJniEnv(m_jvm, attached);
  34. }
  35. JniCallback::~JniCallback() {
  36. jboolean attached_thread = JNI_FALSE;
  37. JNIEnv* env = getJniEnv(&attached_thread);
  38. assert(env != nullptr);
  39. if(m_jcallback_obj != nullptr) {
  40. env->DeleteGlobalRef(m_jcallback_obj);
  41. }
  42. releaseJniEnv(attached_thread);
  43. }
  44. // @lint-ignore TXT4 T25377293 Grandfathered in
  45. } // namespace ROCKSDB_NAMESPACE