Victor Grazi
Victor Grazi

Reputation: 16520

Is there any way to get notifications in process when a thread changes state?

Is there any way to get notifications in process when a thread changes state? I am writing a program that monitors thread state changes. I can poll each thread frequently but I would prefer something more reactive.

Upvotes: 1

Views: 240

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533920

The code you thread runs needs to be injected with code to make a call back which the state changes. You could do this by changing the code as @宏杰李 suggests or injecting the code with Instrumentation however polling the threads is likely to be simplest.

NOTE: The thread's state only tells you it's desired state from a JVM point of view. It doesn't show you

  • is it blocked on a blocking IO operation?
  • has it been context switched
  • has it been interrupted by the OS or the BIOS
  • has it been stopped for GC or code replacement
  • is it waiting for a lock on a static initialiser block. e.g. if it blocked waiting for the class to initialise it says it is RUNNING.

BTW Even the OS polls CPUs to see what they are doing, typically 100 times per second.

Upvotes: 0

宏杰李
宏杰李

Reputation: 12178

yes, use conditional variable, here is an example:

import java.util.concurrent.locks.*;
public class CubbyHole2 {
    private int contents;
    private boolean available = false;  // this is your state
    private Lock aLock = new ReentrantLock(); // state must be protected by lock
    private Condition condVar = aLock.newCondition(); // instead of polling, block on a condition

    public int get(int who) {
        aLock.lock();  
        try {
            // first check state
            while (available == false) {
                try {
                    // if state not match, go to sleep
                    condVar.await(); 
                } catch (InterruptedException e) { }
            }
            // when status match, do someting

            // change status
            available = false;
            System.out.println("Consumer " + who + " got: " +
                                contents);
            // wake up all sleeper than wait on this condition
            condVar.signalAll();  
        } finally {
            aLock.unlock();
            return contents;
        }
    }

    public void put(int who, int value) {
                    aLock.lock();
    try {
        while (available == true) {
            try {
                condVar.await();
            } catch (InterruptedException e) { }
        }
        contents = value;
        available = true;
        System.out.println("Producer " + who + " put: " +
                            contents);
        condVar.signalAll();
        } finally {
            aLock.unlock();
        }
    }
}

Upvotes: 1

Related Questions