Skip to content

Commit b39d1bc

Browse files
committed
Avoid duplicated job execution when an execution is waiting to start
1 parent 9f4424f commit b39d1bc

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

spring-batch-core/src/main/java/org/springframework/batch/core/JobExecution.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,14 @@ public StepExecution createStepExecution(String stepName) {
259259
return stepExecution;
260260
}
261261

262+
/**
263+
* Test if this {@link JobExecution} indicates that it is waiting to start.
264+
* @return true if the status is {@link BatchStatus#STARTING}.
265+
*/
266+
public boolean isStarting() {
267+
return status == BatchStatus.STARTING;
268+
}
269+
262270
/**
263271
* Test if this {@link JobExecution} indicates that it is running.
264272
* Note that this does not necessarily mean that it has been persisted.

spring-batch-core/src/main/java/org/springframework/batch/core/repository/support/SimpleJobRepository.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ public JobExecution createJobExecution(String jobName, JobParameters jobParamete
123123

124124
// check for running executions and find the last started
125125
for (JobExecution execution : executions) {
126-
if (execution.isRunning() || execution.isStopping()) {
126+
if (execution.isStarting() || execution.isRunning() || execution.isStopping()) {
127127
throw new JobExecutionAlreadyRunningException("A job execution for this job is already running: "
128128
+ jobInstance);
129129
}

spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryIntegrationTests.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,25 @@ public void testSaveExecutionContext() throws Exception {
174174
// assertEquals(ctx, retrievedJobExec.getExecutionContext());
175175
}
176176

177+
/*
178+
* If JobExecution is waiting to start, exception will be thrown in attempt
179+
* to create new execution.
180+
*/
181+
@Transactional
182+
@Test
183+
public void testStartingJobRejectsAnotherJobExecution() throws Exception {
184+
job.setRestartable(true);
185+
JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), jobParameters);
186+
187+
try {
188+
jobRepository.createJobExecution(job.getName(), jobParameters);
189+
fail();
190+
}
191+
catch (JobExecutionAlreadyRunningException e) {
192+
// expected
193+
}
194+
}
195+
177196
/*
178197
* If JobExecution is already running, exception will be thrown in attempt
179198
* to create new execution.

0 commit comments

Comments
 (0)