简体   繁体   中英

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?

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.

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();
        }
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM