Skip to content

Job-scoped beans are not usable from worker threads of multi-threaded steps and parallel flows #5576

Closed

Description

@fmbenhassine

A job-scoped bean cannot be used from any thread other than the one that executes the Job. This fails with ScopeNotActiveException / IllegalStateException: No context holder available for job scope in two cases:

  1. In the worker threads of a multi-threaded step (a step configured with a TaskExecutor).
  2. In the threads used to run parallel flows (FlowBuilder#split(TaskExecutor)).

StepScope does not have this limitation: the step context is registered on worker threads, for example by ChunkOrientedStep, StepContextRepeatCallback and AsyncItemProcessor. Nothing registers the job context on these threads. JobSynchronizationManager is only registered from AbstractJob#execute, on the thread that runs the job (ThreadLocal-based).

The javadoc of JobSynchronizationManager says it is the responsibility of every Job implementation to make a JobContext available on every thread involved in a job execution, including worker threads from a pool. The framework does not do this for the two cases above.

This was first reported in #4782, where it was combined with a request for a new @FlowScope. This issue covers only the job scope propagation.

Environment

Spring Batch main (as of eab562f), embedded HSQL job repository.

Steps to reproduce

Define a @JobScope bean and use it from (a) the processor of a multi-threaded chunk-oriented step and (b) two steps running in parallel flows:

@Bean
@JobScope
JobScopedBean jobScopedBean() {
      return new JobScopedBean();
}

@Bean
Job multiThreadedStepJob(JobRepository jobRepository, PlatformTransactionManager transactionManager,
              JobScopedBean jobScopedBean) {
      Step step = new ChunkOrientedStepBuilder<Integer, Integer>(jobRepository, 1)
              .reader(new ListItemReader<>(List.of(1, 2, 3, 4)))
              .processor(item -> {
                      jobScopedBean.getId(); // fails on worker threads
                      return item;
              })
              .writer(new ListItemWriter<>())
              .transactionManager(transactionManager)
              .taskExecutor(new SimpleAsyncTaskExecutor())
              .build();
      return new JobBuilder("multiThreadedStepJob", jobRepository).start(step).build();
}

A complete reproducer, as a JUnit test, is attached below (JobScopeMultiThreadingTests). It contains a sequential control job, which passes, and the two cases above, which fail.

Expected behavior

The job-scoped bean is resolved on every thread taking part in the job execution, and all threads see the same instance. The jobs complete successfully.

Actual behavior

The jobs fail:

org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.jobScopedBean': Scope 'job' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton
Caused by: java.lang.IllegalStateException: No context holder available for job scope

Minimal Complete Reproducible example

JobScopeMultiThreadingTests.java
package org.springframework.batch.core.scope;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.configuration.support.JdbcDefaultBatchConfiguration;
import org.springframework.batch.core.job.Job;
import org.springframework.batch.core.job.JobExecution;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.job.parameters.JobParameters;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.Step;
import org.springframework.batch.core.step.builder.ChunkOrientedStepBuilder;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.infrastructure.item.support.ListItemReader;
import org.springframework.batch.infrastructure.item.support.ListItemWriter;
import org.springframework.batch.infrastructure.repeat.RepeatStatus;
import org.springframework.batch.infrastructure.support.DatabaseType;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.jdbc.support.JdbcTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * Tests that a {@link JobScope job-scoped} bean can be used from the threads that take
 * part in a job execution, and that all of them see the same instance.
 */
class JobScopeMultiThreadingTests {

	/**
	 * Identities of the job-scoped bean instances seen by the job's components. Static
	 * because the components are lambdas that capture the job-scoped proxy.
	 */
	private static final Set<String> seenInstances = ConcurrentHashMap.newKeySet();

	@BeforeEach
	void setUp() {
		seenInstances.clear();
	}

	@Test
	void testJobScopedBeanInSequentialSteps() throws Exception {
		JobExecution jobExecution = runJob("sequentialStepsJob");

		assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus(), failures(jobExecution));
		assertEquals(1, seenInstances.size());
	}

	@Test
	void testJobScopedBeanInMultiThreadedStep() throws Exception {
		JobExecution jobExecution = runJob("multiThreadedStepJob");

		assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus(), failures(jobExecution));
		assertEquals(1, seenInstances.size());
	}

	@Test
	void testJobScopedBeanInParallelFlows() throws Exception {
		JobExecution jobExecution = runJob("parallelFlowsJob");

		assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus(), failures(jobExecution));
		assertEquals(1, seenInstances.size());
	}

	private JobExecution runJob(String jobName) throws Exception {
		try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
				JobConfiguration.class)) {
			Job job = context.getBean(jobName, Job.class);
			return context.getBean(JobOperator.class).start(job, new JobParameters());
		}
	}

	private static String failures(JobExecution jobExecution) {
		return "Job failed with: " + jobExecution.getAllFailureExceptions();
	}

	public static class JobScopedBean {

		private final String id = Integer.toHexString(System.identityHashCode(this));

		// accessed through a getter as the bean is injected as a scoped proxy
		public String getId() {
			return this.id;
		}

	}

	@Configuration
	static class JobConfiguration extends JdbcDefaultBatchConfiguration {

		@Bean
		@JobScope
		JobScopedBean jobScopedBean() {
			return new JobScopedBean();
		}

		@Bean
		DataSource dataSource() {
			return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
				.addScript(DatabaseType.HSQL.getProductSchema())
				.generateUniqueName(true)
				.build();
		}

		@Bean
		PlatformTransactionManager transactionManager(DataSource dataSource) {
			return new JdbcTransactionManager(dataSource);
		}

		@Bean
		Job sequentialStepsJob(JobRepository jobRepository, PlatformTransactionManager transactionManager,
				JobScopedBean jobScopedBean) {
			return new JobBuilder("sequentialStepsJob", jobRepository)
				.start(taskletStep("step1", jobRepository, transactionManager, jobScopedBean))
				.next(taskletStep("step2", jobRepository, transactionManager, jobScopedBean))
				.build();
		}

		@Bean
		Job multiThreadedStepJob(JobRepository jobRepository, PlatformTransactionManager transactionManager,
				JobScopedBean jobScopedBean) {
			Step step = new ChunkOrientedStepBuilder<Integer, Integer>(jobRepository, 1)
				.reader(new ListItemReader<>(List.of(1, 2, 3, 4)))
				.processor(item -> {
					seenInstances.add(jobScopedBean.getId());
					return item;
				})
				.writer(new ListItemWriter<>())
				.transactionManager(transactionManager)
				.taskExecutor(new SimpleAsyncTaskExecutor())
				.build();
			return new JobBuilder("multiThreadedStepJob", jobRepository).start(step).build();
		}

		@Bean
		Job parallelFlowsJob(JobRepository jobRepository, PlatformTransactionManager transactionManager,
				JobScopedBean jobScopedBean) {
			Flow flow1 = new FlowBuilder<Flow>("flow1")
				.start(taskletStep("step1", jobRepository, transactionManager, jobScopedBean))
				.build();
			Flow flow2 = new FlowBuilder<Flow>("flow2")
				.start(taskletStep("step2", jobRepository, transactionManager, jobScopedBean))
				.build();
			Flow parallelFlows = new FlowBuilder<Flow>("parallelFlows").split(new SimpleAsyncTaskExecutor())
				.add(flow1, flow2)
				.build();
			return new JobBuilder("parallelFlowsJob", jobRepository).start(parallelFlows).end().build();
		}

		private Step taskletStep(String name, JobRepository jobRepository,
				PlatformTransactionManager transactionManager, JobScopedBean jobScopedBean) {
			return new StepBuilder(name, jobRepository).tasklet((contribution, chunkContext) -> {
				seenInstances.add(jobScopedBean.getId());
				return RepeatStatus.FINISHED;
			}, transactionManager).build();
		}

	}

}

Activity

  1. added this to the 6.1.0-RC1 milestone on Oct 6, 2026
  2. self-assigned this
    on Oct 6, 2026
  3. added a commit that references this issue on Oct 6, 2026
    c95b8dc
  4. added a commit that references this issue on Oct 7, 2026
    2f9e839
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

for: backport-to-6.0.xin: corerelated-to: multi-threadingtype: bug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions