BlockingQueue - ArrayBlockingQueue vs. LinkedBlockingQueue

1 . LinkedBlockingQueue: This is a LinkedList Implementation but Not Exactly JDK Implementation of LinkedList It uses static inner class Node to maintain Links between elements. Check the following Constructor for LinkedBlockingQueue.

public LinkedBlockingQueue(int capacity)
  if (capacity < = 0) throw new IllegalArgumentException();
  this.capacity = capacity;
  // Maintains a underlying linkedlist. ( Use when size is not known )
  last = head = new Node< E >(null);   

The following static inner class Node Used to Maintain Links

static class Node<E> {
    E item;
    Node<E> next;
    Node(E x) { item = x; }

Read More about LinkedBlockingQueue Here

2. ArrayBlockingQueue: ArrayBlockingQueue is implemented using a backing array. Constructor for ArrayBlockingQueue

public ArrayBlockingQueue(int capacity, boolean fair)
    if (capacity < = 0)
        throw new IllegalArgumentException();
    this.items = new Object[capacity]; // Maintains a underlying array
    lock = new ReentrantLock(fair);
    notEmpty = lock.newCondition();
    notFull =  lock.newCondition();

The Biggest Difference between ArrayBlockingQueue and LinkedBlockingQueue is clear from constructor one has underlying data structure Array and other linkedList. LinkedBlockingQueue has a putLock and a takeLock for insertion and removal respectively but ArrayBlockingQueue uses only 1 lock. ArrayBlockingQueue uses single-lock double condition algorithm and LinkedBlockingQueue is variant of the "two lock queue" algorithm and it has 2 locks 2 conditions ( takeLock , putLock).

Two Lock Queue algorithm is being used by LinkedBlockingQueue Implementation.Thus LinkedBlockingQueue's take and put can work concurrently, but this is not the case with ArrayBlockingQueue. The reason for using a single lock in ArrayBlockingQueue is ,ArrayBlockingQueue has to avoid overwriting entries so that it needs to know where the start and the end is. A LinkedBlockQueue doesn't need to know this as it lets the GC worry about cleaning up Nodes in the queue.

Read More about ArrayBlockingQueue Here


core java 12 Java Concurrent Packages 12


Explore Tutu'rself