elklepo
elklepo

Reputation: 517

Lock thread while resource is empty

Very simplified version of My project. Multiple instances of MyThread try to get and remove one element form Set defined in MyWorker class and do some work with it.

In the rest of my code (not pasted here) I have at least one thread that is filling Set in MyWorker so there is no risk that ParseNextPendingElement() will never find element in Set.

My problem is that I don't know how to "lock" thread on empty set. Now I've implemented primitive delay after failed access to Set. How can I achieve both waiting for Set to have at least one element and not stress CPU while waiting?

public class MyThread implements Runnable {
    private MyWorker worker;

    //constructors, get, set, etc.

    public void run() {
        worker.ParseNextPendingElement();
    }
}

private static class MyWorker {
    private Set set;

    //constructors, get, set, etc.

    public void ParseNextPendingElement() {
        Object elemToParse;

        while(1) {
            synchronized(set) {
                if(!set.isEmpty()) {
                    elemToParse = set.remove();
                    break;
                }
            }

            // BRUTAL workaround to not stress CPU while waiting for
            // at least one element in set.
            Thread.delay(100);
        }

        // Do some stuff with elemToParse
        return;
    }
}

Upvotes: 1

Views: 114

Answers (1)

Moshe Arad
Moshe Arad

Reputation: 3733

If you wish to have a thread behavior that will enter into waiting state and will come back when you have a new input, that's sounds like a job for LinkedBlockingQueue from the java.util.concurrent package instead of just a Set.

LinkedBlockingQueue has a method take() that will enter a thread to waiting state if the queue is empty, and will come back when it'll have new items in it.

Upvotes: 3

Related Questions