Java listen on Thread state

1.6k Views Asked by At

For debug purpose I would like to listen on a threads state. I want it to print a notification whenever the thread is waiting on a log and whenever it 'resumes'.

4

There are 4 best solutions below

2
Hanmaslah On

The method getState() of a thread returns a Thread.State which can be:

NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING or TERMINATED

Thread.State state = getThreadInQuestion().getState();
if(state == Thread.State.WAITING) {
  System.out.println("Waiting");
} else if(state == Thread.State.RUNNABLE) {
  System.out.println("Running");
}else{
  System.out.println("Neither running nor waiting")
}
0
Naili On

I don't think there a good way to monitor a thread state 'programmatically'. However, you can use one of the profiling tools like VisualVM (There is many others but I personally prefer this one) .

You can also refer to this official documentation on how you can monitor your application's threads using VisualVM.

0
Michael Gantman On

You can extend Thread class and in your class you can allow a listener to be registered with your class and it will be notified by your Thread each time the state is changed. It's possible but I think it will become very complex solution as you will have to insure that all threads in your code are using your class and not regular one. In short IMHO its not worth the truble

0
Frankie On

Given that you can't listen to private volatile int threadStatus; on java.lang.Thread as that variable is managed by native code the only way I can think of would be to have a parallel thread with a method that would run every x milliseconds/seconds and output appropriately.

// keep old values in a map like this
HashMap<Thread, ThreadStatus> threadMap;

// loop all threads
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
ArrayList<Thread> threadArrayList = new ArrayList<>(threadSet);
for (Thread thread : threadArrayList) {
    // check if thread.getState() has changed, update accordingly
}

Notice that besides not being efficient you would miss a lot of ThreadStatus changes that would happen sub-millisecond.