How to catch all the states of the thread and log them?

There is a code:

public static void main(String[] args) throws InterruptedException { Thread threadForLogging = new Thread(); LoggingStateThread loggingStateThread = new LoggingStateThread(threadForLogging); loggingStateThread.start(); threadForLogging.start(); threadForLogging.interrupted(); } 

The LoggingStateThread is written as:

 public class LoggingStateThread extends Thread { public Thread threadForLogging; public LoggingStateThread(Thread threadForLogging) { this.threadForLogging = threadForLogging; setDaemon(true); } @Override public void run() { State st; st = threadForLogging.getState(); System.out.println(st); do { if (!st.equals(threadForLogging.getState())) { st = threadForLogging.getState(); System.out.println(st); } } while (!st.equals(State.TERMINATED)); } } 

I understand that the threads go in their own order. That's the question: how not to miss these states? This should be done by the LoggingStateThread class.

And yes, I understand that this can be done with the help of special libraries, but I want to figure out for myself how it works.

  • @Vladislav Pyatkov did not understand the answer. I kind of know what getState () returns ... - Yukon
  • Then describe what it means not to miss. If you want some specific order, then you need to explicitly set it with locks, if not, what does it mean "not to miss"? - Vladislav Pyatkov September
  • @Vladislav Pyatkov in the thread in this case passes through three states: "NEW", "RUNNABLE" and "TERMINATED". Just run the code and everything will become clear. - Yukon
  • I think this can be done by java.lang.reflect.Proxy or Javassist to write a proxy and obviously throw a notification. - Vladislav Pyatkov

1 answer 1

The answer: no way. You cannot "subscribe" to stream states. Imagine that you started the stream, it has already worked, and the logger is tupit somewhere with the output of the previous message (for example, you redirected the standard output to a file on a network drive and there you just have to flush, and the network has fallen off). Do you suggest the current thread to wait in the RUNNABLE state until the logging thread stops blunting? But if the current thread waits, then it will not be anyway RUNNABLE, it will be WAITING. Trends are too low-level structure and they should work quickly regardless of external conditions.

If you really want to, you can write a java-agent that will intercept calls to the methods of the java.lang.Thread class and add the appropriate logs. But even that is difficult, because, for example, the thread can be transferred to the WAITING state in different ways.