Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

TimeUnit.MILLISECONDS: lock timeouts in milliseconds

Use `TimeUnit.MILLISECONDS` to give `tryLock` a timeout in milliseconds. Each call gets its own timeout and can acquire the lock immediately.

Version: Java SE 21

Syntax

import java.util.concurrent.TimeUnit;

// In a method that catches or declares InterruptedException:
boolean acquired = lock.tryLock(100L, TimeUnit.MILLISECONDS);

TimeUnit.MILLISECONDS is an enum constant of TimeUnit in the java.util.concurrent package. A millisecond is one thousandth of a second. The constant specifies a unit, not a duration: in lock.tryLock(100L, TimeUnit.MILLISECONDS), 100L is the long amount and the second argument makes it 100 ms.

For ReentrantLock, the tryLock(long, TimeUnit) overload can return true immediately if it acquires the lock, or false if the timeout expires before it acquires it. If the thread is already interrupted on entry or is interrupted during acquisition, the method throws InterruptedException; catch or declare it. The no-argument tryLock() does not wait. Specifying milliseconds does not guarantee that the method returns at exactly 100 ms.

Passing 100L, TimeUnit.MILLISECONDS to both calls gives each attempt its own 100 ms timeout, not one shared budget. Call unlock() in a finally block only for a lock you acquired. In the example, if the second attempt returns false or throws, the outer finally still releases the first lock.

Examples

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class MillisecondTryLock {
    public static void main(String[] args) throws InterruptedException {
        var first = new ReentrantLock();
        var second = new ReentrantLock();

        if (!first.tryLock(100L, TimeUnit.MILLISECONDS)) {
            System.out.println("First lock unavailable");
            return;
        }
        try {
            if (!second.tryLock(100L, TimeUnit.MILLISECONDS)) {
                System.out.println("Second lock unavailable");
                return;
            }
            try {
                System.out.println("Both locks acquired");
            } finally {
                second.unlock();
            }
        } finally {
            first.unlock();
        }
    }
}

Result

Both locks acquired

There is no contention, so the program acquires both locks without waiting. The output shows successful acquisition, not that 100 ms elapsed.

Related lessons

  • Java · Lesson 58 · Intermediate · Version: 2

Sources