Spring / Spring7 Intermediate to Advanced Interview questions
Why doesn't a @Scheduled method run concurrently with itself by default in Spring?
Spring's default scheduling infrastructure behind @EnableScheduling uses a single-threaded TaskScheduler unless the application explicitly supplies its own multi-threaded one. With only one thread servicing every @Scheduled method, if a given execution takes longer than the method's fixed interval, the next trigger simply waits its turn in that single thread's queue rather than starting a second, overlapping execution.
@Configuration public class SchedulingConfig { @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(5); // now different @Scheduled methods can overlap return scheduler; } }
Even after configuring a larger pool so different scheduled methods can run concurrently with each other, a single scheduled method is still, by design, treated as one logical unit of periodic work rather than something meant to have multiple copies of itself running at once - Spring doesn't automatically re-enter a method's next scheduled execution while a previous run of that same method is still in flight, since that would typically indicate the fixed interval is too aggressive for the work involved rather than something to paper over with concurrency. Genuine concurrent execution of the same logical task, if actually needed, has to be built deliberately - for example, by having the scheduled trigger just enqueue independent units of work onto a separate worker pool.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
