Tuesday 17 March 2020

Get currently running threads in Java

Approach 1: Using Thread.getAllStackTraces() method.
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

Approach 2: Using enumerate method of root thread group.

Approach looks like below.
a.   Get the thread group of currently running thread.
b.   Get root thread group by traversing reverse
c.    Call enumerate method on root thread group to get all the active threads.

public static List<Thread> getCurrentlyRunningThreads_approach2() {

	// Get root thread group
	ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup();
	ThreadGroup parentThreadGroup;
	while ((parentThreadGroup = currentThreadGroup.getParent()) != null) {
		currentThreadGroup = parentThreadGroup;
	}

	int activeThreadsCount = currentThreadGroup.activeCount();
	Thread[] activeThreads = new Thread[activeThreadsCount * 2];

	currentThreadGroup.enumerate(activeThreads, true);

	return Arrays.asList(activeThreads);

}

App.java
package com.sample.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class App {

	public static List<Thread> getCurrentlyRunningThreads_approach1() {
		Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
		return new ArrayList<>(threadSet);
	}

	public static List<Thread> getCurrentlyRunningThreads_approach2() {

		// Get root thread group
		ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup();
		ThreadGroup parentThreadGroup;
		while ((parentThreadGroup = currentThreadGroup.getParent()) != null) {
			currentThreadGroup = parentThreadGroup;
		}

		int activeThreadsCount = currentThreadGroup.activeCount();
		Thread[] activeThreads = new Thread[activeThreadsCount * 2];

		currentThreadGroup.enumerate(activeThreads, true);

		return Arrays.asList(activeThreads);

	}

	public static void main(String args[]) {
		List<Thread> threads = getCurrentlyRunningThreads_approach1();

		threads.stream().forEach(thread -> {
			if (thread != null)
				System.out.println(thread.getName());
		});

		System.out.println("\n");

		threads = getCurrentlyRunningThreads_approach2();

		threads.stream().forEach(thread -> {
			if (thread != null)
				System.out.println(thread.getName());
		});

	}

}

Output
Signal Dispatcher
main
Finalizer
Reference Handler


Reference Handler
Finalizer
Signal Dispatcher
main

You may like

No comments:

Post a Comment