Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java concurrency - is monitor blocked?

Is there a way to tell from one thread (say the one which locks a monitor object) if another thread is blocked / waiting on same monitor?

Example scenario -

a "collector" thread reads data from a shared object, while the "updater" thread might be blocked and waiting for the collection to end. I would like the collector to know that when he finishes collecting, a possible data update is pending which yield the collected data might already be invalid.

In my case collecting might be a time consuming operation, and also in the next stage the "collector" thread analyzes the data for some more time, which might be a redundant operation in many cases where the data is invalid.

like image 566
Elist Avatar asked Nov 18 '25 18:11

Elist


1 Answers

Is there a way to tell from one thread (say the one which locks a monitor object) if another thread is block/waiting on same monitor?

No, not from the object itself. You can, as @Evgeniy mentioned, use other of the java.util.concurrent.locks.* classes which allow you to view the queued members, but not from a synchronized (lock) type of object monitor.

I would like the collector to know that when he finishes collecting, a possible data update is pending which yield the collected data might already be invalid.

How about having a BlockingQueue of updates so the collector could check the queue and see if it is non-empty. The updater thread(s) would just be adding Update information to the BlockingQueue and the collector would dequeue the updates and make the adjustments. It then could check the length of the queue and make a decision about whether or not it needed to move into analysis mode.

private BlockingQueue<Update> updateQueue = new LinkedBlockingQueue<Update>();
...
// called by the updater thread(s)
public void updateData(Update update) {
    updateQueue.put(update);
}
// called by the collector
public void collect() {
    while (!Thread.currentThread().isInterrupted()) {
        Update update = updateQueue.take();
        updateValues(update);
        if (updateQueue.isEmpty()) {
           analyzeData();
        }
    }
}

Regardless of how you do it, you are going to need to account for the new data update using some other mechanism as opposed to checking all threads' blocked state.

like image 76
Gray Avatar answered Nov 21 '25 07:11

Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!