Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ArrayBlockingQueue(int): queue capacity versus worker keep-alive

Create a fixed-capacity queue with two slots, and distinguish that queue limit from a zero idle keep-alive time for excess pool workers.

Version: Java SE 21

Syntax

public ArrayBlockingQueue(int capacity)

// Java SE 21: a queue with two slots for waiting tasks
new ThreadPoolExecutor(1, 2, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(2))

In Java SE 21, ArrayBlockingQueue(int) in java.util.concurrent creates an empty, array-backed blocking queue with fixed capacity. Passing 2 allows up to two elements at once; zero or a negative capacity throws IllegalArgumentException. Elements are removed in FIFO order, but the default policy does not guarantee the access order of waiting threads. Use the ArrayBlockingQueue(int, boolean) overload with true for FIFO access among waiting threads.

When the queue is full, offer(E) returns false without waiting for space, whereas put(E) waits for space unless interrupted. When used as a ThreadPoolExecutor work queue, the capacity bounds the number of tasks waiting in the queue, not the number of workers or the total number of accepted tasks.

In the ThreadPoolExecutor constructor, 0L is the value zero as a long literal. Plain 0 is an int literal and also works for this parameter by widening to long. TimeUnit.MILLISECONDS is an enum constant in java.util.concurrent; one millisecond is one thousandth of a second. A keep-alive time of 0L in this unit means idle workers above corePoolSize do not wait for new work before terminating. It is not a task deadline. Core workers do not time out by default, and allowCoreThreadTimeOut(true) requires a positive keep-alive time.

Examples

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        var queue = new ArrayBlockingQueue<String>(2);
        System.out.println(queue.offer("A"));
        System.out.println(queue.offer("B"));
        System.out.println(queue.offer("C"));

        try (var executor = new ThreadPoolExecutor(
                1, 2, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(2))) {
            System.out.println("keepAliveMs=" + executor.getKeepAliveTime(TimeUnit.MILLISECONDS));
        }
    }
}

Result

true
true
false
keepAliveMs=0

The standalone queue accepts two elements and rejects the third (`false`). The executor has its own two-slot queue. The program reads back `keepAliveMs=0` without running tasks or measuring worker lifetime.

Related lessons

  • Java · Lesson 37 · Advanced · Version: 2
  • Java · Lesson 42 · Advanced · Version: 2

Sources