Quick revision
The short answer
We replace the Timer with a single-thread ScheduledExecutorService that has a named thread factory, schedule refreshCache() with scheduleAtFixedRate(..., 0, 60, TimeUnit.SECONDS), and wrap the body in try and catch so one failure does not cancel all later runs. We shut the executor down when the application stops. In a Spring application, @Scheduled(fixedRate = 60000) on a bean is simpler, because Spring owns the scheduler and its lifecycle.
What to remember
In this answer, we migrated a Timer to a single-thread ScheduledExecutorService with a named thread, scheduled the refresh every 60 seconds with a TimeUnit, wrapped it in try and catch so failures are logged and later runs continue, and shut the executor down with shutdown() and awaitTermination(). In Spring we would rather use @Scheduled(fixedRate = 60000), which hands the threads and their lifecycle to the framework.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We replace the Timer with a single-thread ScheduledExecutorService that has a named thread factory, schedule refreshCache() with scheduleAtFixedRate(..., 0, 60, TimeUnit.SECONDS), and wrap the body in try and catch so one failure does not cancel all later runs. We shut the executor down when the application stops. In a Spring application, @Scheduled(fixedRate = 60000) on a bean is simpler, because Spring owns the scheduler and its lifecycle.
Why this question is asked
This kind of migration comes up whenever a team inherits older code: a cache refresh, a token renewal or a cleanup job started with new Timer() in a constructor. The interviewer wants more than a mechanical rewrite. They want to hear why each change matters: what happens when the refresh fails, which thread runs it, and what happens when the application shuts down. In this answer, we will look at what is wrong with the original line, write the plain Java replacement step by step, add a clean shutdown, and then write the Spring version and compare the two.
1What the Original Code Does and Where It Breaks
The original code creates a Timer and asks it to call refreshCache() immediately and then every 60,000 milliseconds, one minute. The Timer owns one thread, which runs the anonymous TimerTask.
Notice three weaknesses. If refreshCache() throws a runtime exception even once, say because the database was briefly unavailable, the timer thread dies and the cache is never refreshed again, with nothing in the logs. The thread has a generic name, Timer-0, so in a thread dump we cannot tell what it does. And nobody ever cancels the Timer, so its non-daemon thread can keep the JVM alive at shutdown or leak across redeploys in an application server.
2Create the Executor With a Named Thread
We create a scheduled executor with one thread, which is enough for one job and keeps the same one-at-a-time behaviour. We give it a thread factory so the thread has a meaningful name. On Java 21 and later, the Thread.ofPlatform() builder makes this one line.
The reason for the name is operational: when the refresh hangs, a thread dump shows a thread called cache-refresh stuck in a JDBC call, which tells us at once where to look. On older Java versions we write a small ThreadFactory that calls new Thread(r, "cache-refresh") instead.
3Schedule the Task and Catch Exceptions
Now we schedule the refresh, passing a lambda instead of an anonymous TimerTask, and express the period in seconds with a TimeUnit so the number reads clearly.
- Executor thread wakes at the planned time0s, 60s, 120s ...
- Call refreshCache()inside try
- Did it throw?YesLog the error and keep the scheduleNoNothing to do
- Plan the next run60 seconds after the previous planned start
4 steps in order. Play them, or step through them one at a time.
The try and catch is the most important line in the migration. A ScheduledExecutorService survives a throwing task, unlike a Timer, but it still suppresses every later run of that task and keeps the exception inside the ScheduledFuture, where nobody looks. By catching and logging, a failed refresh becomes one error line, and the next run a minute later gets a fresh chance.
Notice also that scheduleAtFixedRate on an executor never runs two refreshes at once. If one refresh takes 70 seconds, the next starts as soon as it ends rather than overlapping. If we would rather always have a full minute of rest between refreshes, scheduleWithFixedDelay is the better choice.
4Shut the Executor Down on Stop
An executor's threads live until we stop them. In a long-running service, we stop the executor when the application stops, giving a running refresh a little time to finish.
Where stop() is called depends on the environment: a JVM shutdown hook, a servlet context listener, or the framework's lifecycle. Without this step the thread leaks, which in an application server that redeploys the application means one more stray thread per deploy.
5The Spring Version
If the code lives in a Spring application, we let Spring do the scheduling. We put the method on a bean, annotate it with @Scheduled and turn scheduling on once with @EnableScheduling.
| Concern | Timer | ScheduledExecutorService | @Scheduled |
|---|---|---|---|
Failure in refreshCache() | All later runs stop | Caught and logged, next run happens | Caught and logged, next run happens |
| Thread name | Timer-0 | cache-refresh | From thread-name-prefix |
| Shutdown | Never | shutdown() and awaitTermination() | Handled by the context |
| Clock | Wall clock | Monotonic | Monotonic |
Spring Boot configures a ThreadPoolTaskScheduler for these methods, with one thread by default, which we can change with spring.task.scheduling.pool.size and spring.task.scheduling.thread-name-prefix. Spring starts it with the context and stops it on shutdown, so Step 3 disappears. For repeating tasks Spring's default error handler logs an exception and keeps the schedule, but the explicit try and catch is still worth keeping, because it lets us choose the message, add metrics and decide what counts as a failure.
6Follow-up questions
Why a single-thread executor instead of a pool?
There is only one job, and we do not want two refreshes running at once. A single thread keeps the behaviour of the original Timer for this job while fixing its failure handling. If the same executor later runs several unrelated jobs, a small pool stops one from delaying the others.
Should the first run happen at time 0?
The original runs immediately, so we keep 0 to preserve behaviour. In a service, an immediate refresh during startup can slow startup or fail before dependencies are ready, so many teams use an initial delay of a few seconds, or initialDelay on @Scheduled.
What if the application runs several instances?
Each instance runs its own refresh. For a local cache that is what we want. For a job that must run once per cluster, such as sending a report, we need a lock, for example a database lock or a library such as ShedLock, or a dedicated scheduler.
7Conclusion
In this answer, we migrated a Timer to a single-thread ScheduledExecutorService with a named thread, scheduled the refresh every 60 seconds with a TimeUnit, wrapped it in try and catch so failures are logged and later runs continue, and shut the executor down with shutdown() and awaitTermination(). In Spring we would rather use @Scheduled(fixedRate = 60000), which hands the threads and their lifecycle to the framework.
Open with
I would replace the Timer with Executors.newSingleThreadScheduledExecutor and pass a thread factory that names the thread cache-refresh, so it is easy to find in thread dumps. Then I would call scheduleAtFixedRate with a lambda, an initial delay of 0 and a period of 60 seconds using TimeUnit.SECONDS.
Then, if they want more
The key change is wrapping refreshCache in try and catch and logging the error. With the Timer, one runtime exception kills the timer thread and the cache silently stops refreshing forever. The executor survives a failure, but it would still suppress all later runs of that task, so the catch is what keeps the schedule alive.
I would also shut the executor down when the application stops, with shutdown, awaitTermination for a few seconds and shutdownNow as a fallback, so the thread does not leak or block the JVM from exiting. If this is a Spring application, I would skip all of that and put @Scheduled with fixedRate 60000 on a bean method with @EnableScheduling.
Spring Boot provides the TaskScheduler, I can size it and name its threads with properties, and Spring stops it with the context. I would still keep the try and catch for clear logging and metrics.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Batch reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Migrate this code to a modern alternative and explain the improvements:": https://scrivio-interview-library.netlify.app/spring-boot/scheduling/a93721582a/