ArrayBlockingQueue exceeds given capacity

Posted by Wojciech Reszelewski on Stack Overflow See other posts from Stack Overflow or by Wojciech Reszelewski
Published on 2012-10-23T22:49:11Z Indexed on 2012/10/23 23:00 UTC
Read the original article Hit count: 179

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

© Stack Overflow or respective owner

Related posts about java

Related posts about concurrency