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'.
-
One cheap way of doing this is to take a thread dump using tools like `jstack`. – Kedar Mhaswade Aug 31 '16 at 20:05
4 Answers
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.

- 24,627
- 10
- 79
- 121
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")
}

- 736
- 1
- 8
- 14
-
This is only a partial answer possibly not even that. How do you know when to print? That is, how will the OP know that the thread has resumed? – bradimus Aug 31 '16 at 20:15
-
Also, where do you want to place this code? Thread state can change very often. Your code is not a listener declaration, it is kinda monitor – Sergei Rybalkin Aug 31 '16 at 21:17
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.

- 1,564
- 3
- 20
- 27
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

- 7,315
- 2
- 19
- 36