Block actions till list becomes non-empty with java.util.concurrent

Niklas Lechler :

I need your help. I should use the java.util.concurrent package in my exercise but I don't know how to do it. The question is only about the get method.

public String getInput() {
        if (inputList.isEmpty()) return null;
        String input = inputList.get(0);
        inputList.remove(0);
        return input;
}

How do I need to write the code to wait till the given list (variable: inputList) becomes non-empty?

Greetings

pero_hero :

you could try using the LinkedBlockingDeque class from the java.util.concurrent package which implements the BlockingDequeinterface.

it lets you add items to the BlockingDeque and the take* methods block until there is an element available and remove it after fetching. Have a look at the Javadoc

Here is an example:

public class Queue {

    BlockingDeque<String> inputList = new LinkedBlockingDeque<>();

    public String getInput() {
        try {
            System.out.println("waiting on queue");
            String input = inputList.takeFirst();
            System.out.println("taken " + input);
            return input;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {

        Queue queue = new Queue();

        new Thread(() -> {
            try {
                Thread.sleep(4000);
                queue.inputList.add("string");
                System.out.println("added string");
                Thread.sleep(2000);
                queue.inputList.add("string1");
                System.out.println("added string 1");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        for (int i = 0; i < 2; i++){
            queue.getInput();
        }
    }

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=477757&siteId=1