Manually close the JNI libraries

Runtime does not support repeatedly doing JNI->CreateVM, thus we need to
manually clean up the dynamic linking loader so that gtests would not
fail.

Bug: 25785594
Change-Id: I15d55e142b9f91735b1c94c8cb43cc854ec49ffe
(cherry picked from commit 46bc2a7c6c5ae6b4d5fc065d607208193c2d162e)
diff --git a/runtime/common_runtime_test.cc b/runtime/common_runtime_test.cc
index d514cad..ce0d503 100644
--- a/runtime/common_runtime_test.cc
+++ b/runtime/common_runtime_test.cc
@@ -409,6 +409,26 @@
   (*icu_cleanup_fn)();
 
   Runtime::Current()->GetHeap()->VerifyHeap();  // Check for heap corruption after the test
+
+  // Manually closing the JNI libraries.
+  // Runtime does not support repeatedly doing JNI->CreateVM, thus we need to manually clean up the
+  // dynamic linking loader so that gtests would not fail.
+  // Bug: 25785594
+  if (runtime_->IsStarted()) {
+    {
+      // We retrieve the handle by calling dlopen on the library. To close it, we need to call
+      // dlclose twice, the first time to undo our dlopen and the second time to actually unload it.
+      // See man dlopen.
+      void* handle = dlopen("libjavacore.so", RTLD_LAZY);
+      dlclose(handle);
+      CHECK_EQ(0, dlclose(handle));
+    }
+    {
+      void* handle = dlopen("libopenjdk.so", RTLD_LAZY);
+      dlclose(handle);
+      CHECK_EQ(0, dlclose(handle));
+    }
+  }
 }
 
 std::vector<std::string> CommonRuntimeTest::GetLibCoreDexFileNames() {