{
	"id": "b3b77b4b-7d89-4ec0-8a40-5f94cf81570f",
	"created_at": "2026-10-14T02:03:32.046732Z",
	"updated_at": "2026-11-22T02:24:53.027264Z",
	"deleted_at": null,
	"sha1_hash": "cdcef45f825b5207a4c1e772d41caf01a8238aa1",
	"title": "How to Delay Code Execution in Java: A Comprehensive Guide",
	"llm_title": "How to Delay Code Execution in Java: A Comprehensive Guide",
	"authors": "",
	"file_creation_date": "0001-01-01T00:00:00Z",
	"file_modification_date": "0001-01-01T00:00:00Z",
	"file_size": 142461,
	"plain_text": "https://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\nHow to Delay Code Execution in Java: A Comprehensive Guide\n\nPublished: 2026-06-07 · Archived: 2026-10-14 02:02:06 UTC\n\nTable of Contents#\n\n1. Thread.sleep(): Basic Blocking Delay\n\n2. Object.wait(): Delaying with Lock Release\n\n3. ScheduledExecutorService: Enterprise-Grade Scheduling\n\n4. Timer and TimerTask: Legacy Scheduling (Avoid When Possible)\n\n5. CompletableFuture: Asynchronous Delays\n\n6. Spring Framework's @Scheduled: Declarative Scheduling\n\n7. Reactive Programming (Project Reactor): Non-Blocking Delays\n\n8. Comparison of Delay Methods\n\n9. General Best Practices\n\n10. Conclusion\n\n11. References\n\n1. Thread.sleep(): Basic Blocking Delay#\n\nThread.sleep()  is the simplest method to pause execution of the current thread. It’s widely used for quick, one-off delays\n\nbut has important limitations.\n\nHow It Works#\n\nWhen called,  Thread.sleep(long milliseconds)  pauses the current thread for the specified duration. Unlike\n\nObject.wait() , it does not release any locks held by the thread—meaning other threads will remain blocked from\n\naccessing synchronized resources during the sleep period.\n\nExample Usage#\n\nimport java.util.concurrent.TimeUnit;\n \npublic class SleepExample {\n    public static void main(String[] args) {\n        System.out.println(\"Task started at: \" + System.currentTimeMillis());\n        \n        try {\n            // Use TimeUnit for readability instead of raw milliseconds\n\nTimeUnit.SECONDS.sleep(2);\n        } catch (InterruptedException e) {\n            // Restore interrupted status for higher-level code to handle\n            Thread.currentThread().interrupt();\n            System.err.println(\"Thread interrupted during sleep: \" + e.getMessage());\n        }\n\nSystem.out.println(\"Task resumed at: \" + System.currentTimeMillis());\n\nPage 1 of 10\n\nhttps://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\n}\n}\n\nCommon Use Cases#\n\nSimple, short delays in non-critical code (e.g., test simulations, console apps).\n\nBasic retry logic for low-stakes operations.\n\nBest Practices#\n\nHandle  InterruptedException : Always catch this checked exception, and restore the thread’s interrupted status\n\nwith  Thread.currentThread().interrupt()  so higher-level code can react.\n\nPrefer  TimeUnit : Use  TimeUnit.SECONDS.sleep(2)  instead of  Thread.sleep(2000)  for improved readability.\n\nAvoid in Critical Sections: Never use  sleep()  in synchronized blocks/methods—it holds locks and can lead to\n\ndeadlocks or performance bottlenecks.\n\nSkip for Precise Timing:  sleep()  is not guaranteed to wake up exactly on schedule (OS scheduler delays may\n\noccur), so avoid it for real-time applications.\n\n2. Object.wait(): Delaying with Lock Release#\n\nObject.wait()  is designed for thread coordination, allowing a thread to pause while releasing the object’s monitor lock.\n\nThis makes it ideal for scenarios where you need to pause a thread without blocking others from accessing shared resources.\n\nKey Differences from Thread.sleep()#\n\nFeature\n\nLock Behavior\n\nContext Requirement\n\nWake-Up Trigger\n\nExample Usage#\n\npublic class WaitExample {\n\nThread.sleep()\n\nHolds all locks\n\nNone\n\nOnly timeout or interrupt\n\nprivate final Object lock = new Object();\n    private boolean conditionMet = false;\n \n    public void delayWithWait() {\n\nObject.wait()\n\nReleases the object monitor\n\nMust be called in a synchronized block\n\nTimeout, interrupt, or  notify() / notifyAll()\n\nsynchronized (lock) {\n            try {\n                // Wait for up to 3 seconds, or until condition is met\n                while (!conditionMet) {\n                    lock.wait(3000);\n                }\n                System.out.println(\"Resumed after wait condition was met or timeout\");\n            } catch (InterruptedException e) {\n                Thread.currentThread().interrupt();\n                System.err.println(\"Thread interrupted during wait: \" + e.getMessage());\n            }\n\nPage 2 of 10\n\nhttps://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\n}\n    }\n \n    public void setConditionMet() {\n        synchronized (lock) {\n            conditionMet = true;\n            lock.notifyAll(); // Wake up waiting threads\n        }\n    }\n}\n\nHandling Spurious Wakeups#\n\nThreads can wake up prematurely from  wait()  for no reason (called spurious wakeups). Always wrap  wait()  in a loop\n\nto recheck the condition before proceeding.\n\nBest Practices#\n\nCall in a Synchronized Block:  wait()  requires the thread to hold the object’s monitor, so always use it inside a\n\nsynchronized  block/method.\n\nUse  notifyAll()  Judiciously: Prefer  notifyAll()  over  notify()  to avoid missing wakeups when multiple\n\nthreads are waiting.\n\nRecheck Conditions: Always verify the wakeup condition in a loop to handle spurious wakeups.\n\n3. ScheduledExecutorService: Enterprise-Grade Scheduling#\n\nPart of the  java.util.concurrent  package,  ScheduledExecutorService  is the gold standard for production-grade\n\nscheduling. It addresses many limitations of legacy tools like  Timer  by supporting multi-threaded execution, flexible\n\nscheduling policies, and robust exception handling.\n\nWhy Prefer Over Timer?#\n\nMulti-Threaded: Uses a thread pool to execute multiple scheduled tasks simultaneously.\n\nException Safety: Unlike  Timer , a failed task does not crash the entire scheduler.\n\nFlexible Scheduling: Supports one-time tasks, fixed-delay intervals, and fixed-rate intervals.\n\nCore Scheduling Methods#\n\nOne-Time Task Scheduling#\n\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;\n \npublic class ScheduledExecutorExample {\n    public static void main(String[] args) {\n        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);\n        \n        // Schedule a task to run after 5 seconds\n        executor.schedule(() -\u003e {\n            System.out.println(\"One-time task executed at: \" + System.currentTimeMillis());\n\nPage 3 of 10\n\nhttps://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\n}, 5, TimeUnit.SECONDS);\n        \n        // Shutdown executor after tasks complete (or use awaitTermination)\n        executor.shutdown();\n\n}\n}\n\nFixed-Delay Scheduling#\n\nRuns tasks with a fixed delay between the end of one task and the start of the next:\n\n// Run task every 2 seconds after the previous task finishes\nexecutor.scheduleWithFixedDelay(() -\u003e {\n    System.out.println(\"Fixed delay task executed at: \" + System.currentTimeMillis());\n}, 0, 2, TimeUnit.SECONDS);\n\nFixed-Rate Scheduling#\n\nRuns tasks at fixed time intervals, regardless of how long each task takes:\n\n// Run task every 2 seconds, starting immediately\n\nexecutor.scheduleAtFixedRate(() -\u003e {\n    System.out.println(\"Fixed rate task executed at: \" + System.currentTimeMillis());\n}, 0, 2, TimeUnit.SECONDS);\n\nBest Practices#\n\nShut Down the Executor: Always call  executor.shutdown()  to release thread pool resources when tasks are no\n\nlonger needed.\n\nHandle Task Exceptions: Wrap task code in a try-catch block to prevent unhandled exceptions from breaking\n\nsubsequent tasks.\n\nTune Thread Pool Size: Use  Executors.newScheduledThreadPool(n)  where  n  matches the number of concurrent\n\ntasks you expect to run.\n\nAvoid Long-Running Tasks: Fixed-rate scheduling can lead to task backlogs if tasks take longer than the interval.\n\nUse fixed-delay instead for long-running tasks.\n\n4. Timer and TimerTask: Legacy Scheduling (Avoid When Possible)#\n\nTimer  is a legacy class for scheduling tasks, but it’s largely replaced by  ScheduledExecutorService  due to its critical\n\nlimitations.\n\nHow It Works#\n\nUses a single thread to execute all scheduled tasks.\n\nFails silently if a task throws an uncaught exception (the entire  Timer  stops working).\n\nExample Usage#\n\nPage 4 of 10\n\nhttps://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\nimport java.util.Timer;\n\nimport java.util.TimerTask;\n\npublic class TimerExample {\n\npublic static void main(String[] args) {\n\nTimer timer = new Timer();\n\n// Schedule task to run after 3 seconds\n\ntimer.schedule(new TimerTask() {\n\n@Override\n\npublic void run() {\n\nSystem.out.println(\"Timer task executed at: \" + System.currentTimeMillis());\n\n}\n\n}, 3000);\n\n// Cancel timer after 5 seconds\n\ntimer.schedule(new TimerTask() {\n\n@Override\n\npublic void run() {\n\ntimer.cancel();\n\n}\n\n}, 5000);\n\n}\n\n}\n\nLimitations and When to Avoid#\n\nSingle Thread: Cannot handle concurrent tasks efficiently.\n\nFragile: A single uncaught exception in any task stops the entire  Timer .\n\nNo Support for Modern Concurrency: Lacks features like thread pooling and flexible scheduling policies.\n\nAvoid  Timer  in new code—use  ScheduledExecutorService  instead.\n\n5. CompletableFuture: Asynchronous Delays#\n\nCompletableFuture  (introduced in Java 8) allows you to delay asynchronous tasks without blocking the calling thread.\n\nThis is ideal for building non-blocking workflows.\n\nExample Usage#\n\nimport java.util.concurrent.CompletableFuture;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class CompletableFutureDelayExample {\n\npublic static void main(String[] args) {\n\nSystem.out.println(\"Main thread continues executing...\");\n\n// Schedule an async task to run after 4 seconds\n\nCompletableFuture.runAsync(() -\u003e {\n\ntry {\n\nTimeUnit.SECONDS.sleep(4);\n\nPage 5 of 10\n\nhttps://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\nSystem.out.println(\"Async delayed task executed at: \" + System.currentTimeMillis());\n\n} catch (InterruptedException e) {\n\nThread.currentThread().interrupt();\n\n}\n\n});\n\n// Main thread can do other work here\n\nSystem.out.println(\"Main thread is not blocked!\");\n\n// Prevent JVM from exiting before task completes\n\ntry {\n\nTimeUnit.SECONDS.sleep(5);\n\n} catch (InterruptedException e) {\n\nThread.currentThread().interrupt();\n\n}\n\n}\n\n}\n\nUse Cases#\n\nAsynchronous retries in non-blocking applications.\n\nDelaying background tasks without affecting the main thread’s responsiveness.\n\n6. Spring Framework's @Scheduled: Declarative Scheduling#\n\nFor Spring applications, the  @Scheduled  annotation provides a declarative way to schedule periodic tasks. It eliminates\n\nboilerplate code and integrates seamlessly with Spring’s dependency injection.\n\nEnabling Scheduling#\n\nFirst, add  @EnableScheduling  to your Spring configuration class:\n\nimport org.springframework.context.annotation.Configuration;\n\nimport org.springframework.scheduling.annotation.EnableScheduling;\n\n@Configuration\n\n@EnableScheduling\n\npublic class SchedulingConfig {\n\n}\n\nScheduling Types with Examples#\n\nFixed Delay#\n\nRuns tasks with a fixed delay between the end of one task and the start of the next:\n\nimport org.springframework.scheduling.annotation.Scheduled;\n\nimport org.springframework.stereotype.Component;\n\n@Component\n\npublic class ScheduledTasks {\n\nPage 6 of 10\n\nhttps://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\n@Scheduled(fixedDelay = 2000) // 2 seconds delay after task finishes\n\npublic void fixedDelayTask() {\n\nSystem.out.println(\"Fixed delay task executed at: \" + System.currentTimeMillis());\n\n}\n\n}\n\nFixed Rate#\n\nRuns tasks at a fixed interval, regardless of task duration:\n\n@Scheduled(fixedRate = 2000) // Run every 2 seconds\n\npublic void fixedRateTask() {\n\nSystem.out.println(\"Fixed rate task executed at: \" + System.currentTimeMillis());\n\n}\n\nCron Expression#\n\nFor complex scheduling (e.g., run at 3 AM every weekday):\n\n@Scheduled(cron = \"0 0 3 ? * MON-FRI\", zone = \"UTC\")\n\npublic void cronTask() {\n\nSystem.out.println(\"Cron task executed at: \" + System.currentTimeMillis());\n\n}\n\nBest Practices#\n\nUse Time Zones: Specify a  zone  in cron expressions to avoid timezone-related issues.\n\nHandle Exceptions: Wrap task code in try-catch blocks to prevent unhandled exceptions from breaking subsequent\n\nruns.\n\nExternalize Config: Use  @Value(\"${task.fixedDelay}\")  to inject delay values from configuration files (e.g.,\n\napplication.properties ).\n\n7. Reactive Programming (Project Reactor): Non-Blocking Delays#\n\nFor reactive applications (e.g., Spring WebFlux), Project Reactor provides non-blocking delay methods that integrate\n\nseamlessly with reactive streams. These methods do not block threads, making them ideal for high-throughput systems.\n\nExample Usage#\n\nMono.delay()#\n\nDelays emission of a single value:\n\nimport reactor.core.publisher.Mono;\n\nimport java.time.Duration;\n\npublic class ReactiveDelayExample {\n\npublic static void main(String[] args) {\n\nMono.delay(Duration.ofSeconds(3))\n\nPage 7 of 10\n\nhttps://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\n.then(Mono.fromRunnable(() -\u003e \n                System.out.println(\"Non-blocking mono task executed at: \" + System.currentTimeMillis())\n            ))\n            .subscribe();\n        \n        // Keep JVM alive\n        try {\n            Thread.sleep(4000);\n        } catch (InterruptedException e) {\n            Thread.currentThread().interrupt();\n        }\n    }\n}\n\nFlux.delayElements()#\n\nDelays emission of each element in a stream:\n\nimport reactor.core.publisher.Flux;\nimport java.time.Duration;\n \npublic class FluxDelayExample {\n    public static void main(String[] args) {\n        Flux.range(1, 3)\n            .delayElements(Duration.ofSeconds(1))\n            .subscribe(i -\u003e \n                System.out.println(\"Emitted element \" + i + \" at: \" + System.currentTimeMillis())\n            );\n        \n        try {\n            Thread.sleep(4000);\n        } catch (InterruptedException e) {\n            Thread.currentThread().interrupt();\n        }\n    }\n}\n\nUse Cases#\n\nNon-blocking retries in reactive APIs.\n\nThrottling emissions in high-throughput reactive streams.\n\n8. Comparison of Delay Methods#\n\nThread Lock Primary Use\nMethod Type Pros Cons\nSafety Behavior Cases\n\nSimple, short Easy to use, Blocks\nHolds\nThread.sleep() Blocking Yes delays in non- readable with thread, no\nlocks\ncritical code TimeUnit lock release\n\nPage 8 of 10\n\nhttps://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\nThread Lock Primary Use\nMethod Type Pros Cons\nSafety Behavior Cases\n\nReleases Thread Requires\nReleases locks,\nObject.wait() Blocking Yes object coordination synchronized\nflexible\nmonitor with timeouts context\n\nTask- Enterprise-\nMulti-threaded, Requires\nspecific grade\nScheduledExecutorService Async/Blocking Yes robust exception executor\nthread scheduling,\nhandling shutdown\nhandling periodic tasks\n\nSingle- Fragile,\nLegacy code\nTimer/TimerTask Async/Blocking Yes threaded Simple setup single-\nmaintenance\nexecution threaded\n\nRequires\nNon- Integrates with\nAsynchronous careful\nCompletableFuture Async Yes blocking CompletableFuture\ntask delays exception\ncaller API\nhandling\n\nSpring\nManaged Declarative,\nDeclarative enterprise Spring-\nSpring @Scheduled Yes by supports cron\nAsync apps, periodic specific\nSpring expressions\ntasks\n\nHigh- Reactor-\nReactive Fully non-\nNon-blocking throughput specific\nProject Reactor Yes thread blocking, high\nAsync reactive learning\nmodel throughput\napplications curve\n\n9. General Best Practices#\n\n1. Choose the Right Tool: Match the delay method to your use case (e.g.,  ScheduledExecutorService  for production\n\nscheduling, reactive methods for WebFlux apps).\n\n2. Avoid Blocking in Non-Blocking Contexts: Never use  Thread.sleep()  in reactive code—use Project Reactor’s\n\nnon-blocking delays instead.\n\n3. Clean Up Resources: Always shut down executors and timers to prevent resource leaks.\n\n4. Externalize Delay Values: Use configuration files instead of hardcoding delays for easy adjustments.\n\n5. Test Delay Logic: Use libraries like Awaitility or Mockito to test delay-dependent code without waiting for real time.\n\n10. Conclusion#\n\nDelaying code execution in Java is a common task, but the method you choose can drastically impact your application’s\n\nperformance and reliability. From basic  Thread.sleep()  to enterprise-grade  ScheduledExecutorService  and reactive\n\ndelays, each approach has unique strengths.\n\nKey takeaways:\n\nUse  Thread.sleep()  for simple, low-stakes delays.\n\nPage 9 of 10\n\nhttps://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\nPrefer  ScheduledExecutorService  over  Timer  for all production scheduling.\n\nUse  Object.wait()  for thread coordination where lock release is needed.\n\nFor Spring apps, leverage  @Scheduled  for declarative scheduling.\n\nIn reactive systems, use Project Reactor’s non-blocking delays to maintain high throughput.\n\nBy following the best practices outlined here, you can ensure your delay logic is thread-safe, efficient, and maintainable.\n\n11. References#\n\n1. Java Thread.sleep() Documentation\n\n2. Java Object.wait() Documentation\n\n3. ScheduledExecutorService Documentation\n\n4. Spring @Scheduled Annotation Documentation\n\n5. Project Reactor Delay Documentation\n\n6. Java Concurrency in Practice (Book) – Chapter 6 on task execution and scheduling.\n\nSource: https://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette\n\nPage 10 of 10",
	"extraction_quality": 1,
	"language": "EN",
	"sources": [
		"MITRE"
	],
	"origins": [
		"web"
	],
	"references": [
		"https://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette"
	],
	"report_names": [
		"#google_vignette"
	],
	"threat_actors": [
		{
			"id": "eb3f4e4d-2573-494d-9739-1be5141cf7b2",
			"created_at": "2022-10-25T16:07:24.471018Z",
			"updated_at": "2026-11-22T02:00:23.5063Z",
			"deleted_at": null,
			"main_name": "Cron",
			"aliases": [],
			"source_name": "ETDA:Cron",
			"tools": [
				"Catelites",
				"Catelites Bot",
				"CronBot",
				"TinyZBot"
			],
			"source_id": "ETDA",
			"reports": null
		}
	],
	"ts_created_at": 1791943412,
	"ts_updated_at": 1795314293,
	"ts_creation_date": 0,
	"ts_modification_date": 0,
	"files": {
		"pdf": "https://archive.orkl.eu/cdcef45f825b5207a4c1e772d41caf01a8238aa1.pdf",
		"text": "https://archive.orkl.eu/cdcef45f825b5207a4c1e772d41caf01a8238aa1.txt",
		"img": "https://archive.orkl.eu/cdcef45f825b5207a4c1e772d41caf01a8238aa1.jpg"
	},
	"iocs": [
		{
			"type": "domain",
			"value": "application.properties",
			"count": 1,
			"flags": [],
			"some_flags": []
		},
		{
			"type": "domain",
			"value": "www.javathinking.com",
			"count": 11,
			"flags": [
				"in_url_host"
			],
			"some_flags": [
				"in_url_host"
			]
		},
		{
			"type": "url",
			"value": "https://www.javathinking.com/blog/how-to-delay-code-execution-in-java/#google_vignette",
			"count": 11,
			"flags": [],
			"some_flags": []
		}
	]
}