Multithreading: ScheduledExecutorService.schedule delays a task

schedule(task, delay, unit) runs a task once after a fixed delay on a background pool thread, without blocking the caller. A latch is the clean way to wait for that delayed task to actually finish before reading its result.

Code
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
String[] result = new String[1];
CountDownLatch latch = new CountDownLatch(1);
scheduler.schedule(() -> {
    result[0] = "scheduled task ran";
    latch.countDown();
}, 20, TimeUnit.MILLISECONDS);
latch.await();
scheduler.shutdown();
System.out.println(result[0]);
Output
scheduled task ran
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms