micronaut-projects / micronaut-core

Micronaut Application Framework
http://micronaut.io
Apache License 2.0
6k stars 1.04k forks source link

Fix race condition in task scheduling #10892

Closed yawkat closed 3 weeks ago

yawkat commented 3 weeks ago

Under some circumstances, ExecutableMethodProcessor.process may be called during or even after the StartupEvent is fired. In that case, scheduled methods may be ignored or there may be a ConcurrentModificationException.

This patch moves the schedule logic into its own method, called by a class ScheduleTaskRunnable that guards the schedule logic using an AtomicBoolean so that it is run only once. Inside process(), the task is created, registered in a ConcurrentHashMap and, if the StartupEvent has already been fired, invoked. Inside the StartupEvent listener, all previously registered tasks are invoked.

This ensures that the ScheduleTaskRunnable is invoked at least once.

yawkat commented 3 weeks ago

The diff is unfortunately pretty big, but you can ignore scheduleTask. It just contains the code that was previously in scheduleTasks.

sonarcloud[bot] commented 3 weeks ago

Quality Gate Failed Quality Gate failed

Failed conditions
1 New Critical Issues (required ≤ 0)

See analysis details on SonarCloud

Catch issues before they fail your Quality Gate with our IDE extension SonarLint