| 16 | import java.util.LinkedList; |
| 17 | |
| 18 | public class LinkedBlockingQueue<T> extends AbstractQueue<T> |
| 19 | implements BlockingQueue<T> { |
| 20 | private final Object collectionLock; |
| 21 | private final LinkedList<T> storage; |
| 22 | private final int capacity; |
| 23 | |
| 24 | public LinkedBlockingQueue() { |
| 25 | this(Integer.MAX_VALUE); |
| 26 | } |
| 27 | |
| 28 | public LinkedBlockingQueue(int capacity) { |
| 29 | collectionLock = new Object(); |
| 30 | this.capacity = capacity; |
| 31 | storage = new LinkedList<T>(); |
| 32 | } |
| 33 | |
| 34 | // should be synchronized on collectionLock before calling |
| 35 | private void handleRemove() { |
| 36 | collectionLock.notifyAll(); |
| 37 | } |
| 38 | |
| 39 | // should be synchronized on collectionLock before calling |
| 40 | private void handleAdd() { |
| 41 | collectionLock.notifyAll(); |
| 42 | } |
| 43 | |
| 44 | // should be synchronized on collectionLock before calling |
| 45 | private void blockTillNotFull() throws InterruptedException { |
| 46 | blockTillNotFull(Long.MAX_VALUE); |
| 47 | } |
| 48 | |
| 49 | // should be synchronized on collectionLock before calling |
| 50 | private void blockTillNotFull(long maxWaitInMillis) throws InterruptedException { |
| 51 | if (capacity > storage.size()) { |
| 52 | return; |
| 53 | } |
| 54 | |
| 55 | long startTime = 0; |
| 56 | if (maxWaitInMillis != Long.MAX_VALUE) { |
| 57 | startTime = System.currentTimeMillis(); |
| 58 | } |
| 59 | long remainingWait = maxWaitInMillis; |
| 60 | while (remainingWait > 0) { |
| 61 | collectionLock.wait(remainingWait); |
| 62 | |
| 63 | if (capacity > storage.size()) { |
| 64 | return; |
| 65 | } else if (maxWaitInMillis != Long.MAX_VALUE) { |
| 66 | remainingWait = maxWaitInMillis - (System.currentTimeMillis() - startTime); |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // should be synchronized on collectionLock before calling |
| 72 | private void blockTillNotEmpty() throws InterruptedException { |
| 73 | blockTillNotEmpty(Long.MAX_VALUE); |
| 74 | } |
| 75 |
nothing calls this directly
no outgoing calls
no test coverage detected