Jamal H
Jamal H

Reputation: 1094

Is the ArrayBlockingQueue add method instant?

For an ArrayBlockingQueue in Java, does queue.add(element) ever lock up the thread it is in? I have an application with dozens of threads running that will all put information into one ArrayBlockingQueue. The threads cannot afford to be locked up for any short amount of time. If they are all putting objects into the queue, will the add method instantly move on and let the queue put the object into itself in the future or will it wait until it actually is put inside the queue?

Upvotes: 0

Views: 196

Answers (3)

gati sahu
gati sahu

Reputation: 2626

Yes when you call add method in ArrayBlockingQueue it will take lock to do the operation or else how it will make threadsafe. How you will put your object to any shared variable in multi-threaded environment.You need synchronization.You can check some non-blocking collection (can create own linked list).Where you will add your value then a single daemon thread will read one by one and put in queue.

JAVA Implementation

add method internally call offer.If you don't want to wait more than a given time you can use public boolean tryLock(long timeout, TimeUnit unit)

public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

Upvotes: 1

serdroid
serdroid

Reputation: 166

In ArrayBlockingQueue concurrent operations guarded with java.util.concurrent.locks.ReentrantLock. And operations are synchronous. When you add an item to the queue add operation returns after enqueue operation completed.

Upvotes: 0

Anurag Sharma
Anurag Sharma

Reputation: 2605

ArrayBlockingQueue is implementation of Queue which additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

add method inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and throwing an IllegalStateException if this queue is full.

Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.

Once created, the capacity cannot be changed.

Upvotes: 1

Related Questions