Skip to content

@Scheduled methods in beans created by FactoryBeans are not cancelled #24629

Closed
@abenneke

Description

@abenneke

It looks like, that beans created by FactoryBeans are passed to ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization, however never get passed to
ScheduledAnnotationBeanPostProcessor.postProcessBeforeDestruction.
Only the FactoryBean itself is checked via ScheduledAnnotationBeanPostProcessor.requiresDestruction (and of course fails to require destruction).

As a consequence, the methods in those beans are still continued to be started in parallel during the close-process of the application context - and of course fail when they try to access other beans, entity manager, transaction support, ... They are however finally stopped once the TaskScheduler is shut down.

Normal beans (without FactoryBeans) are created by AbstractAutowireCapableBeanFactory.doCreateBean, which in the end does registerDisposableBeanIfNecessary.

However beans created via FactoryBeans are created by

FactoryBeanRegistrySupport.doGetObjectFromFactoryBean
FactoryBeanRegistrySupport,getObjectFromFactoryBean
AbstractBeanFactory.getObjectForBeanInstance
AbstractBeanFactory.doGetBean

and never get the DisposableBeanAdapter applied. Hence @Scheduled tasks created by those beans are not cancelled.

Please find a stripped down test case at
https://github.com/abenneke/sandbox/tree/master/spring-scheduled-factory
The ComponentConfiguration creates two ScheduledBeans, one directly and another one via a simple FactoryBean. Both beans have the same testScheduled method to be triggered every 100ms. It also adds a SlowDestroyBean, which simply slows down the application context close process a bit.
When you run the Main program, you see that

  • both testScheduled are executed perfectly while the context is up and running,
  • once the closing process is started, the testScheduled invocation of the normal ScheduledBean are stopped as expected, however
  • the testScheduled invocations of the ScheduledBean created via the FactoryBean continue
  • until eventually the TaskScheduler is stopped

This might be related to #14146

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions