Question

I have created a bean of a class with default (Singleton) scope. Within the class I have a method which is scheduled to be run every hour.

public class TaskService implements InitializingBean {

    @Scheduled(cron="0 0 */1 * * ?")
    public void hourlyReportTask()
    {
        ... code here ...
    }

    public void performAllTasks()
    {
        hourlyReportTask();
        ...
        ...
    }

}

My application config looks something like this,

<bean id="reportService" 
            class="com.tasks.TaskService" />

I am assuming the Thread running the scheduled task will be using the same TaskService bean since its created in singleton scope. What shall happen if the application is currently running hourlyReportTask() and the Spring container kicks off a background scheduled thread to run hourlyReportTask() at the same time. Will it wait for the to get access of the TaskService instance?

Was it helpful?

Solution

The exact same instance is used by both your application and the scheduling service. There is no synchronization so the scheduling service may run that method while your application invokes it.

Pretty much the same way as you would have injected TaskService in something that can be accessed by multiple threads at the same time and those threads call that method concurrently.

There's no black magic behind @Scheduled: it invokes your method the same way as you would manually. If that method is not thread-safe you need to fallback on regular synchronization mechanism in Java (for instance by adding the synchronized keyword to your method declaration).

OTHER TIPS

Spring Singleton, does not mean what you expect from Design Patterns Singleton. In Spring, Singleton means that a bean only has created only one instance (without meaning that another cannot be created) and that instance is used whenever Spring needs that type.

In your case your hourlyReportTask() method would execute twice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top