@Test
  public void testJDOPersistenceManagerCleanup() throws Exception {
    if (isThriftClient == false) {
      return;
    }

    Set<JDOPersistenceManager> objectsBeforeUse = new HashSet<>(getJDOPersistenceManagerCache());
    HiveMetaStoreClient closingClient = new HiveMetaStoreClient(conf);
    closingClient.getAllDatabases();
    closingClient.close();

    MetaStoreTestUtils.waitForAssertion("Checking pm cachesize after client close", () -> {
      Set<JDOPersistenceManager> objectsAfterClose = new HashSet<>(getJDOPersistenceManagerCache());
      objectsAfterClose.removeAll(objectsBeforeUse);

      assertEquals("new objects left in the cache (after closing client)", 0, objectsAfterClose.size());

    }, 500, 30000);

    Set<JDOPersistenceManager> objectsAfterClose = new HashSet<>(getJDOPersistenceManagerCache());
    HiveMetaStoreClient nonClosingClient = new HiveMetaStoreClient(conf);
    nonClosingClient.getAllDatabases();
    // Drop connection without calling close. HMS thread deleteContext
    // will trigger cleanup
    nonClosingClient.getTTransport().close();

    MetaStoreTestUtils.waitForAssertion("Checking pm cachesize after transport close", () -> {
      Set<JDOPersistenceManager> objectsAfterDroppedConnection = new HashSet<>(getJDOPersistenceManagerCache());
      objectsAfterDroppedConnection.removeAll(objectsAfterClose);

      assertEquals("new objects left in the cache (after dropping connection)", 0,
          objectsAfterDroppedConnection.size());

    }, 500, 30000);

    nonClosingClient.close(); //let's close after unit test ran successfully
  }
This method checks if persistence manager cache is cleaned up properly under some circumstances.
There is a chance that cleanup process removes elements created not only by this test, so we don't check
exact equality, instead check that no new elements can be seen in the cache (so newSet.removeAll(oldSet) should be empty).
standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/TestHiveMetaStore.java