GCNotifications { public void subscribe(BiConsumer<Long, ?> printer) { for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { NotificationEmitter emitter = (NotificationEmitter) bean; emitter.addNotificationListener(listener, null, printer); } } GCNotifications(NotificationListener listener); void subscribe(BiConsumer<Long, ?> printer); void unsubscribe();  }
@Test public void triggeredListenerOnGC() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); GCNotifications notif = new GCNotifications(GCNotificationsTest::handleNotification); notif.subscribe((t, s) -> { Assert.assertEquals("GC", s); latch.countDown(); }); System.gc(); Assert.assertTrue(latch.await(200, TimeUnit.MILLISECONDS)); }