Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

TimeUnit.MILLISECONDS — timeouts in milliseconds

Use TimeUnit.MILLISECONDS to tell the timed poll and offer overloads of a blocking queue to interpret the timeout argument in milliseconds.

Version: Java SE 21

Syntax

import java.util.concurrent.TimeUnit;

TimeUnit unit = TimeUnit.MILLISECONDS;

// Both timed calls can throw InterruptedException. Catch it or declare it
// in the enclosing method's throws clause.
// Given a BlockingQueue<E> named queue and a non-null E named element:
boolean inserted = queue.offer(element, 250L, TimeUnit.MILLISECONDS);
E head = queue.poll(250L, TimeUnit.MILLISECONDS);

TimeUnit.MILLISECONDS is an enum constant of java.util.concurrent.TimeUnit. It represents a unit equal to one thousandth of a second, not a duration or timestamp on its own. The argument pair 250L, TimeUnit.MILLISECONDS specifies a wait limit of 250 milliseconds. The operation can succeed earlier; the unit does not guarantee the exact time at which the call returns.

On a BlockingQueue<E>, offer(E, long, TimeUnit) waits for space if necessary. It returns true if it inserts the element, or false if the wait limit expires before space is available. poll(long, TimeUnit) waits for an element if necessary. It removes and returns the head, or returns null if the wait limit expires before an element is available. A BlockingQueue does not accept null elements.

Unlike the timed overloads, offer(E) and poll() do not wait for space or for an element. Both timed overloads throw InterruptedException if the thread is interrupted while waiting. Interruption is not a timeout.

When you need a numeric result in milliseconds, TimeUnit.MILLISECONDS.convert(2L, TimeUnit.SECONDS) returns 2000L. The receiver is the target unit. Converting to a coarser unit truncates toward zero; a conversion that would overflow is capped at the corresponding long limit.

Examples

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

public class MillisecondTimeouts {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(1);

        System.out.println(queue.offer("job", 10L, TimeUnit.MILLISECONDS));
        System.out.println(queue.offer("extra", 10L, TimeUnit.MILLISECONDS));
        System.out.println(queue.poll(10L, TimeUnit.MILLISECONDS));
        System.out.println(queue.poll(10L, TimeUnit.MILLISECONDS));
    }
}

Result

true
false
job
null

One thread uses a queue with room for one element. The first offer succeeds, the second times out, the first poll returns `job`, and the second times out and returns `null`. The example checks results, not elapsed time.

Related lessons

  • Java · Lesson 37 · Advanced · Version: 2

Sources