public void afterTest() {
    if (cachedEnabled || disabled) {
      return;
    }

    PooledByteBufAllocatorMetric metric = PooledByteBufAllocator.DEFAULT.metric();
    List<PoolArenaMetric> heaps = metric.heapArenas();
    List<PoolArenaMetric> directs = metric.directArenas();
    // Wait up to 1 sec before declaring failure since deallocations may happen in background with some delay.
    int checkTimeoutInMs = 1000;

    if (!TestUtils.checkAndSleep(activeDirectAllocations,
        () -> directs.stream().mapToLong(PoolArenaMetric::numActiveAllocations).sum(), checkTimeoutInMs)) {
      long currentActiveDirectAllocations = directs.stream().mapToLong(PoolArenaMetric::numActiveAllocations).sum();
      long currentDirectAllocations = directs.stream().mapToLong(PoolArenaMetric::numAllocations).sum();
      long currentDirectDeallocations = directs.stream().mapToLong(PoolArenaMetric::numDeallocations).sum();
      String message =
          String.format("DirectMemoryLeak: [allocation|deallocation] before test[%d|%d], after test[%d|%d]",
              directAllocations, directDeallocations, currentDirectAllocations, currentDirectDeallocations);
      Assert.assertEquals(message, activeDirectAllocations, currentActiveDirectAllocations);
    }
    if (!TestUtils.checkAndSleep(activeHeapAllocations,
        () -> heaps.stream().mapToLong(PoolArenaMetric::numActiveAllocations).sum(), checkTimeoutInMs)) {
      long currentActiveHeapAllocations = heaps.stream().mapToLong(PoolArenaMetric::numActiveAllocations).sum();
      long currentHeapAllocations = heaps.stream().mapToLong(PoolArenaMetric::numAllocations).sum();
      long currentHeapDeallocations = heaps.stream().mapToLong(PoolArenaMetric::numDeallocations).sum();
      String message = String.format("HeapMemoryLeak: [allocation|deallocation] before test[%d|%d], after test[%d|%d]",
          heapAllocations, heapDeallocations, currentHeapAllocations, currentHeapDeallocations);
      Assert.assertEquals(message, activeHeapAllocations, currentActiveHeapAllocations);
    }
  }
Method to call at any method that is tagged {@link org.junit.After} to verify there is no leak within this test case.
ambry-test-utils/src/main/java/com/github/ambry/utils/NettyByteBufLeakHelper.java