How to check the number of currently running threads in Java? - java

I'm looking for a way to see the number of currently running threads
Through Windows first
Programmatically

This will give you the total number of threads in your VM :
int nbThreads = Thread.getAllStackTraces().keySet().size();
Now, if you want all threads currently executing, you can do that :
int nbRunning = 0;
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getState()==Thread.State.RUNNABLE) nbRunning++;
}
The possible states are enumerated here: Thread.State javadoc
If you want to see running threads not programmaticaly but with a Windows tool, you could use Process Explorer.

You can get all the threads and their stack traces running in the JVM uses Thread.getAllStackTraces()

In response to your following comment
In the following piece of code: while(resultSet.next()) {
name=resultSet.getString("hName"); MyRunnable worker = new
MyRunnable(hName); threadExecutor.execute( worker ); } . My thread
pool has size of 10. I need to make sure that my program working
correctly with multi-threadings & want to check how many threads are
running at a certain moment. How can I do this?
to another answer, I suggest that you profile your code with JVisualVM and check if your thread pool is working as it should. The reason behind this suggestion is that then you don't have to bother with all the other housekeeping threads that JVM manages. Besides what you want to do is why tools like JVisualVM are made for.
If you are new to profiling Java programs, JVisualVM lets you see what goes on under the hood while you are running your code. You can see the Heap, GC activity, inspect the threads running/waiting any sample/profile your cpu or memory usage. There are quite a few plugins as well.

From Windows:
There's bound to be a performance counter for the process that can tell you that.
Programmatically:
There's Thread#activeCount:
Returns an estimate of the number of active threads in the current thread's thread group and its subgroups. Recursively iterates over all subgroups in the current thread's thread group.
Or more directly, ThreadGroup#activeCount:
Returns an estimate of the number of active threads in this thread group and its subgroups.
and ThreadGroup#getParent:
Returns the parent of this thread group.
First, if the parent is not null, the checkAccess method of the parent thread group is called with no arguments; this may result in a security exception.
All of which seem to suggest something along the lines of:
int activeThreadTotalEstimate() {
ThreadGroup group;
ThreadGroup parent;
group = Thread.currentThread().getThreadGroup();
while ((parent = group.getParent()) != null) {
group = parent;
}
return group.activeCount();
}

Code snippet:
import java.util.Set;
import java.lang.Thread.State;
public class ActiveThreads {
public static void main(String args[]) throws Exception{
for ( int i=0; i< 5; i++){
Thread t = new Thread(new MyThread());
t.setName("MyThread:"+i);
t.start();
}
int threadCount = 0;
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for ( Thread t : threadSet){
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup() &&
t.getState() == Thread.State.RUNNABLE){
System.out.println("Thread :"+t+":"+"state:"+t.getState());
++threadCount;
}
}
System.out.println("Thread count started by Main thread:"+threadCount);
}
}
class MyThread implements Runnable{
public void run(){
try{
Thread.sleep(2000);
}catch(Exception err){
err.printStackTrace();
}
}
}
output:
Thread :Thread[main,5,main]:state:RUNNABLE
Thread count started by Main thread:1
Explanation:
Thread.getAllStackTraces().keySet() provides you list of all Threads, which have been started by both Program and System. In absence of ThreadeGroup condition, you will get System thread count if they are active.
Reference Handler, Signal Dispatcher,Attach Listener and Finalizer

Related

How to read all Thread Name, Running on JVM? [duplicate]

Is there any way I can get a list of all running threads in the current JVM (including the threads not started by my class)?
Is it also possible to get the Thread and Class objects of all threads in the list?
I want to be able to do this through code.
To get an iterable set:
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Performance: 0 ms for 12 threads (Azul JVM 16.0.1, Windows 10, Ryzen 5600X).
Get a handle to the root ThreadGroup, like this:
ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parentGroup;
while ((parentGroup = rootGroup.getParent()) != null) {
rootGroup = parentGroup;
}
Now, call the enumerate() function on the root group repeatedly. The second argument lets you get all threads, recursively:
Thread[] threads = new Thread[rootGroup.activeCount()];
while (rootGroup.enumerate(threads, true ) == threads.length) {
threads = new Thread[threads.length * 2];
}
Note how we call enumerate() repeatedly until the array is large enough to contain all entries.
Yes, take a look at getting a list of threads. Lots of examples on that page.
That's to do it programmatically. If you just want a list on Linux at least you can just use this command:
kill -3 processid
and the VM will do a thread dump to stdout.
You can get a lot of information about threads from the ThreadMXBean.
Call the static ManagementFactory.getThreadMXBean() method to get a reference to the MBean.
Have you taken a look at jconsole?
This will list all threads running for a particular Java process.
You can start jconsole from the JDK bin folder.
You can also get a full stack trace for all threads by hitting Ctrl+Break in Windows or by sending kill pid --QUIT in Linux.
You can try something like this:
Thread.getAllStackTraces().keySet().forEach((t) -> System.out.println(t.getName() + "\nIs Daemon " + t.isDaemon() + "\nIs Alive " + t.isAlive()));
and you can obviously get more thread characteristic if you need.
Apache Commons users can use ThreadUtils. The current implementation uses the walk the thread group approach previously outlined.
for (Thread t : ThreadUtils.getAllThreads()) {
System.out.println(t.getName() + ", " + t.isDaemon());
}
To get a list of threads and their full states using the terminal, you can use the command below:
jstack -l <PID>
Which <PID> is the id of process running on your computer. To get the process id of your java process you can simply run the jps command.
Also, you can analyze your thread dump that produced by jstack in TDAs (Thread Dump Analyzer) such fastthread or spotify thread analyzer tool.
In Groovy you can call private methods
// Get a snapshot of the list of all threads
Thread[] threads = Thread.getThreads()
In Java, you can invoke that method using reflection provided that security manager allows it.
Code snippet to get list of threads started by main thread:
import java.util.Set;
public class ThreadSet {
public static void main(String args[]) throws Exception{
Thread.currentThread().setName("ThreadSet");
for ( int i=0; i< 3; i++){
Thread t = new Thread(new MyThread());
t.setName("MyThread:"+i);
t.start();
}
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for ( Thread t : threadSet){
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){
System.out.println("Thread :"+t+":"+"state:"+t.getState());
}
}
}
}
class MyThread implements Runnable{
public void run(){
try{
Thread.sleep(5000);
}catch(Exception err){
err.printStackTrace();
}
}
}
output:
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[ThreadSet,5,main]:state:RUNNABLE
If you need all threads including system threads, which have not been started by your program, remove below condition.
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup())
Now output:
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[Reference Handler,10,system]:state:WAITING
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[ThreadSet,5,main]:state:RUNNABLE
Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[Finalizer,8,system]:state:WAITING
Thread :Thread[Signal Dispatcher,9,system]:state:RUNNABLE
Thread :Thread[Attach Listener,5,system]:state:RUNNABLE
In the java console, hit Ctrl-Break. It will list all threads plus some information about the heap. This won't give you access to the objects of course. But it can be very helpful for debugging anyway.
public static void main(String[] args) {
// Walk up all the way to the root thread group
ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parent;
while ((parent = rootGroup.getParent()) != null) {
rootGroup = parent;
}
listThreads(rootGroup, "");
}
// List all threads and recursively list all subgroup
public static void listThreads(ThreadGroup group, String indent) {
System.out.println(indent + "Group[" + group.getName() +
":" + group.getClass()+"]");
int nt = group.activeCount();
Thread[] threads = new Thread[nt*2 + 10]; //nt is not accurate
nt = group.enumerate(threads, false);
// List every thread in the group
for (int i=0; i<nt; i++) {
Thread t = threads[i];
System.out.println(indent + " Thread[" + t.getName()
+ ":" + t.getClass() + "]");
}
// Recursively list all subgroups
int ng = group.activeGroupCount();
ThreadGroup[] groups = new ThreadGroup[ng*2 + 10];
ng = group.enumerate(groups, false);
for (int i=0; i<ng; i++) {
listThreads(groups[i], indent + " ");
}
}
You can use getAllThreadIds that Returns all live thread IDs. Some threads included in the returned array may have been terminated when this method returns.
ManagementFactory.getThreadMXBean().getAllThreadIds()

Java : Thread Questions

I'm trying to improve my JAVA. Now i have one questions i don't understand about threading.
My trying code is that,
public class MyThread implements Runnable {
private int end;
private String name;
public MyThread(String name, int end) {
this.end = end;
this.name = name;
}
#Override
public void run() {
for (int i = 0; i < end; i++) {
System.out.println(name + " : " + i);
}
}
}
public class ThreadLesson {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyThread("thread1", 6));
Thread thread2 = new Thread(new MyThread("thread2", 5), "thread2");
thread1.start();
thread2.start();
}
}
On lesson output is
thread1 : 0
thread2 : 0
thread2 : 1
thread2 : 2
thread1 : 1
thread2 : 3
thread1 : 2
thread2 : 4
thread1 : 3
thread1 : 4
thread1 : 5
My outout is
Thread1:0
Thread2:0
Thread1:1
Thread1:2
Thread1:3
Thread1:4
Thread1:5
Thread2:1
Thread2:2
Thread2:3
Thread2:4
My Question is,
Why my out is not same lesson output ? There have some problem or who write that lesson just edit output for article to be beaty.
Somewhere in the lesson this might have been written in bold letters . You should not expect same results as shown here. You have started 2 threads by passing 2 different runnables. WIthout proper synchronization, there is no way of telling what the output would be.
Yes, you might find that very odd at the beginning that the values obtained vary greatly. In fact, there is no way to determine the proper output when two or more unsynchronized thread are allowed to run simultaneously.
This can be understood as
When threads are created they are said to be born state, you do not run a thread by using the run() but you use the start(). Now you may ask the reason behind the logic.
It is quite simple, if you use the run() then the processor must run the thread at that moment, which can cause problem. But if you use the start() then you tell the processor that you want to run the thread. Now after this the processor will take care of the thread as soon as it is free to do so.
It must be clear that the modern processors perform a number of task simultaneously. To achieve this, they can use either Round-Robin method or Preemptive scheduling to complete the task.
In time-slicing, each process is given same amount of processor time. Whereas in preemptive scheduling, the task with higher priority is given the preference.
Now when a number of threads run simultaneously then it depends on the operating system to allocate the processor to any thread. So any thread can get the processor which can change the output you see.
Now if the threads are synchronized then the conditions change and the program can have a fixed path.
We can not predict output pattern in this kind of cases as output will be solely depend upon jvm's Thread manager. If you want to have a predicted output you can go for Thread.sleep(timeinml) method as this will provide thread synchronization

Does Java actually run threads in parallel

I would like to understand that does java actually run multiple threads in parallel in a multi core CPU, or there is context switching between threads and only one thread is active and others are waiting for their turn to run.
In other words, is there a possibility that 2 threads are running in parallel???
Because my Thread.currentThread() does not give me a array of threads, but only one thread which is running.
So what is the truth, does only one thread run at a time while others wait or multiple threads can run in parallel, if yes , then why my Thread.currentThread() method return only 1 thread object.
Edit : .....
I have created 2 classes to count numbers
1 class does it synchronously and the other one divides it into two halves and executes the two halves in 2 threads..(intel i5(4 CPUs), 8GB ram)
the code is as follows :
common class :
class Answer{
long ans = 0L;}
Multi Thread execution :
public class Sheet2 {
public static void main(String[] args) {
final Answer ans1 = new Answer();
final Answer ans2 = new Answer();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
for(int i=0;i<=500000; i++) {
ans1.ans = ans1.ans + i;
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
for(int i=500001;i<=1000000; i++) {
ans2.ans = ans2.ans + i;
}
}
});
long l1 = System.currentTimeMillis();
try {
t1.start();t2.start();
t1.join();
t2.join();
long l2 = System.currentTimeMillis();
System.out.println("ans :" + (ans1.ans + ans2.ans) +" in "+(l2-l1) +" milliseconds");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Single Thread execution :
public class Sheet3 {
public static void main(String[] args) {
final Answer ans1 = new Answer();
long l1 = System.currentTimeMillis();
for(int i=0;i<=1000000; i++) {
ans1.ans = ans1.ans + i;
}
long l2 = System.currentTimeMillis();
System.out.println("ans :" + (ans1.ans ) +" in "+(l2-l1) +" milliseconds"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
My Single thread execution is faster than my multi threaded execution, I though the context switching was putting a overhead on the execution initially and hence the multithreaded execution output was slower, now I am having muti core CPU (4 CPU), but still single threaded execution is faster in this example..
Can you please explain the scenario here... is it because my other processes are eating up the other cores and hence my threads are not running in parallel and performing time slicing on the CPU ???
Kindly throw some light on this topic.
Thanks in advance.
Cheers.!!!
In short yes it does run on separate threads. You can test it by creating 100 threads and checking in your process explorer it will say 100 threads. Also you can do some computation in each thread and you will see your multicore processor go upto 100% usage.
Thread.currentThread gives you the current thread you are running from.
When you start your program you are running on the "main" thread.
As soon as you start a new thread
new Thread(myRunnable);
any code located in the myRunnable will run on the new thread while your current thread is is still on the main Thread.
If you check out the API http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html it gives allot more detailed description of the thread.
The actual threading mechanism can vary between CPU architectures. But the real problem is that you're misinterpreting the method name. Thread.currentThread() doesn't return the thread executing at the current moment in time; it returns the thread currently executing the method call, that is, itself.
Yes it does. Run any simple infinite loop on more than one threads and you'll see the cpu usage > 100% on a multi-core CPU.
Yes it does run threads concurrently .That is the very purpose of the multithreading concept .you may find the folowing discussion helpful :
Current Thread Method java
Not a complete answer here, just adding to what others already have said:
The Java Language Specification does not require that threads run in parallel, but it allows them to do so. What actually happens in any given Java Virtual Machine depends on how that JVM is implemented.
Any practical JVM will create one "native" (i.e., operating system) thread for each Java thread, and let the operating system take care of scheduling, locking, waiting, notifying,...

Using threads in Java

I have a portion of code dealing with threads and I want to understand its function in detail. The run method is empty in my example, but lets assume it has some operations to do on a global variable:
import java.io.File;
public class DigestThread extends Thread {
private File input;
public DigestThread(File input) {
this.input = input;
}
public void run() {
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
File f = new File(args[i]);
Thread t = new DigestThread(f);
t.start();
}
}
}
After creating a thread and starting it, will it wait to finish the tasks in the run method before creating/running another thread ?
second question
if a variable has declared in run method that means it will be declared many times because every thread created will do the task in run method , is every thread handles its own varible although variable in each thread are same ?
will it waitng for finish the tasks in run method to creat another
method ?
No. That's the whole point of Multithreading. Every thread has it's own stack of execution. So, when you start a thread, it enters the run() method, and executes it in a different stack, and at the same time the main thread continues execution, in it's own stack.
After that, main thread, can spawn another thread. Thus all the threads run simultaneously, but of course, one at a time, sharing the CPU amongst them, based on the specific CPU allocation algorithm being used.
It's not possible to write down all the details about the execution process of multiple threads here. I would rather suggest to read some tutorials or search for some online resources, regarding the concept of Multithreading. Once clear in concept, move ahead with the implementation in Java.
Here's some tutorials links you can start with: -
Thread Wiki Page
SO Multithreading Wiki Page
Concurrency - Oracle Tutorial
http://www.vogella.com/articles/JavaConcurrency/article.html
Once you start a thread, it will run in a separate thread and the main() thread will continue (it may end before the child thread ends).
If you want the thread to finish before main then you can use the Thread.join method on thread to wait for it.
First, Thread is a single sequential flow of control within a program.
We can execute more than one thread in a program, but there is a life cycle, where you can find out how threads work...
Whenever we call the start() method of Thread it automatically calls the overriden method public void run() and executes the code of the run() method...
Here is a simple example of Thread in Java with ABC and XYZ thread classes
/* Write a program to print having two Thread Class 1) ABC with 1 second 2) XYZ 2 second. 10 times with Extend Constructor */
class ABCThreadConstructor extends Thread {
ABCThreadConstructor(String name) {
super(name);
}
public void run() {
try {
for(int i = 0; i < 10; i++) {
System.out.println("ABC");
Thread.sleep(1000);
}
} catch(InterruptedException ie) {
System.out.println("Interrupted Exception : "+ie);
}
}
}
class XYZThreadConstructor extends Thread {
XYZThreadConstructor(String name) {
super(name);
}
public void run() {
try{
for(int i = 0; i < 10; i++) {
System.out.println("XYZ");
Thread.sleep(2000);
}
} catch(InterruptedException ie) {
System.out.println("Interrupted Exception : "+ie);
}
}
}
class AbcXyzThreadConstructorDemo {
public static void main(String args[]) {
ABCThreadConstructor atc = new ABCThreadConstructor("ABCThreadConstructor");
System.out.println("Thread Name : " + atc.getName());
atc.start();
XYZThreadConstructor xtc = new XYZThreadConstructor("XYZThreadConstructor");
System.out.println("Thread Name : " + xtc.getName());
xtc.start();
}
}
Assuming your question is "After creating a thread and starting it, will the program wait for the thread to finish its run method before creating another thread?"
If that's the case, No the program will not wait. t.start() kicks off the thread and it gets its own chunk of memory and thread priority to run. It will do its operations and then exist accordingly. Your main thread will start the number of threads specified in args before terminating.
If you need the application to wait on the thread then use t.join(). That way the parent thread (the one that runs main) will be joined to the child thread and block until its operation is complete. In this case it sort of defeats the purpose of threading but you can store the thread ID for whatever logic you need and join() later.

How to Obtain Thread Info/Statistics in Java

Title says it all. I have some code which is included below and I am wondering how I would go about obtaining the statistics/information related to the threads (i.e. how many different threads are running, names of the different threads). For consistency sake, image the code is run using 22 33 44 55 as command line arguments.
I am also wondering what the purpose of the try blocks are in this particular example. I understand what try blocks do in general, but specifically what do the try blocks do for the threads.
public class SimpleThreads {
//Display a message, preceded by the name of the current thread
static void threadMessage(String message) {
long threadName = Thread.currentThread().getId();
System.out.format("id is %d: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
String info[];
MessageLoop(String x[]) {
info = x;
}
public void run() {
try {
for (int i = 1; i < info.length; i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
threadMessage(info[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
}
public static void main(String args[])throws InterruptedException {
//Delay, in milliseconds before we interrupt MessageLoop
//thread (default one minute).
long extent = 1000 * 60;//one minute
String[] nargs = {"33","ONE", "TWO"};
if (args.length != 0) nargs = args;
else System.out.println("assumed: java SimpleThreads 33 ONE TWO");
try {
extent = Long.parseLong(nargs[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("First Argument must be an integer.");
System.exit(1);
}
threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop(nargs));
t.start();
threadMessage("Waiting for MessageLoop thread to finish");
//loop until MessageLoop thread exits
int seconds = 0;
while (t.isAlive()) {
threadMessage("Seconds: " + seconds++);
//Wait maximum of 1 second for MessageLoop thread to
//finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > extent) &&
t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
//Shouldn't be long now -- wait indefinitely
t.join();
}
}
threadMessage("All done!");
}
}
you can use VisualVM for threads monitoring. which is included in JDK 6 update 7 and later. You can find visualVm in JDK path/bin folder.
VisualVM presents data for local and remote applications in a tab
specific for that application. Application tabs are displayed in the
main window to the right of the Applications window. You can have
multiple application tabs open at one time. Each application tab
contains sub-tabs that display different types of information about
the application.VisualVM displays real-time, high-level data on
thread activity in the Threads tab.
For the first issue:
Consider using VisualVM to monitor those threads. Or just use your IDEs debugger(eclipse has such a function imo).
I am also wondering what the purpose of the try blocks are in this particular example.
InterruptedExceptions occur if Thread.interrupt() is called, while a thread was sleeping. Then the Thread.sleep() is interrupted and the Thread will jump into the catch-code.
In your example your thread sleeps for 4 seconds. If another thread invokes Thread.interrupt() on your sleeping one, it will then execute threadMessage("I wasn't done!");.
Well.. as you might have understood now, the catch-blocks handle the sleep()-method, not a exception thrown by a thread. It throws a checked exception which you are forced to catch.
If you are not able to use tools like VisualVM (which is very useful, IMHO), you can also dump the thread stack in Java, e.g. to your logfile. I am using such dumps on my server programs, when certain thresholds are crossed. I found doing such snapshots as part of the program very helpful. Gives you some hints on what happened before the system crashes and it is too late to use profilers (deadlock, OutOfMemory, slowdown etc.). Have a look here for the code: Trigger complete stack dump programmatically?

Categories