Question

I've written program solving bounded producer & consumer problem. While constructing ArrayBlockingQueue I defined capacity 100. I'm using methods take and put inside threads. And I've noticed that sometimes I see put 102 times with any take's between them. Why does it happen?

Producer run method:

public void run() {
    Object e = new Object();
    while(true) {
        try {
            queue.put(e);
        } catch (InterruptedException w) {
                System.out.println("Oj, nie wyszlo, nie bij");
        }
        System.out.println("Element added");

    }
}

Consumer run method:

public void run() {
    while(true) {
        try {
            queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Element removed");
    }
}

Part of uniq -c on file with output:

102 Element removed
102 Element added
102 Element removed
102 Element added
102 Element removed
102 Element added
102 Element removed
102 Element added
102 Element removed
102 Element added
102 Element removed
102 Element added
  2 Element removed
  2 Element added
102 Element removed
102 Element added
Was it helpful?

Solution

I defined capacity 100. I'm using methods take and put inside threads. And I've noticed that sometimes I see put 102 times with any take's between them. Why does it happen?

This is most likely a byproduct of race conditions in your output instead of implying that the blocking queue ever has more than 100 entries in the queue. A thread might remove something from the queue after an element is put into the queue but displays the "removed" message before the putter can display the "added" message -- and vice versa. There is no locking between the queue calls and the System.out.println(...) so the order is not guaranteed.

If there is any question, print out queue.size() to see if it ever exceeds 100. The ArrayBlockingQueue will never show you that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top