CountedThreadFactory implements ThreadFactory { @Override public Thread newThread(@NotNull Runnable runnable) { Thread thread = delegate.newThread( () -> { running.incrementAndGet(); try { runnable.run(); } finally { running.decrementAndGet(); terminated.increment(); } }); created.increment(); return thread; } CountedThreadFactory(
      ThreadFactory delegate, MeterRegistry registry, String name, Iterable<Tag> tags); @Override Thread newThread(@NotNull Runnable runnable); static void monitorThreads(
      MeterRegistry registry, ThreadPoolExecutor executor, String name, Iterable<Tag> tags);  }
@Test public void shouldCountCreatedThreads() { ThreadFactory factory = new CountedThreadFactory( Executors.defaultThreadFactory(), registry, CountedThreadFactoryTest.class.getName(), userTags); factory.newThread(() -> {}); assertEquals( registry .get("thread.factory.created") .tags(userTags) .tag("name", CountedThreadFactoryTest.class.getName()) .counter() .count(), 1.0); }
@Test public void shouldCountRunningThreads() throws InterruptedException { ThreadFactory factory = new CountedThreadFactory( Executors.defaultThreadFactory(), registry, CountedThreadFactoryTest.class.getName(), userTags); CountDownLatch runnableTaskStart = new CountDownLatch(1); CountDownLatch runnableTaskComplete = new CountDownLatch(1); Runnable task = () -> { runnableTaskStart.countDown(); try { Assert.assertTrue(runnableTaskComplete.await(10, TimeUnit.SECONDS)); } catch (InterruptedException e) { throw new IllegalStateException("runnable interrupted before completion"); } }; Thread thread = factory.newThread(task); thread.start(); runnableTaskStart.await(); assertEquals( registry .get("thread.factory.running") .tags(userTags) .tag("name", CountedThreadFactoryTest.class.getName()) .gauge() .value(), 1.0); runnableTaskComplete.countDown(); thread.join(); assertEquals( registry .get("thread.factory.running") .tags(userTags) .tag("name", CountedThreadFactoryTest.class.getName()) .gauge() .value(), 0.0); assertFalse(thread.isAlive()); assertNotNull(factory); }