Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions doc/concurrency/rescheduling-task.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# ReschedulingTask — normal rescheduling

## Problem

The scheduler's future is not necessarily done while its callback is executing its final block. The refresh itself has finished, but scheduleNext runs before the callback returns. Replacing the tracked future can therefore cancel the callback that is currently finishing, potentially interrupting its own thread.

## Change

Capture the tracked future before invoking the refresh. In the finally block, detach that exact future with compareAndSet before calling scheduleNext. Do not require the future to report isDone: the refresh has already finished.

```mermaid
sequenceDiagram
participant E as Current callback
participant T as Tracked future
participant S as Scheduler
E->>T: capture predecessor
E->>E: run refresh
E->>T: compareAndSet(predecessor, null)
E->>S: schedule successor
S-->>E: new future
E->>T: publish successor
E->>E: return normally
```

The existing replacement and orphan cancellation logic in scheduleNext remains unchanged. The compareAndSet prevents blindly clearing a different future published after the captured reference was read.

## Scope

This is a targeted fix, not a lifecycle redesign. The original State enum, atomic references, method signatures, and cancellation policy remain unchanged. The existing races involving concurrent disable/enable and future publication are not resolved by this change. In particular, overlapping refreshes across disable/enable cycles remain possible and should be addressed separately.

The test suite starts from the latest develop version, including the logger-based execution short-circuit tests. One regression test verifies that normal continuation does not cancel the predecessor and that disabling still cancels the successor.

Maven tests have not been executed in this environment.
7 changes: 3 additions & 4 deletions src/main/java/org/morphix/lang/thread/ReschedulingTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ private void execute() {
logger.debug("[{}] Scheduler is disabled, skipping execution.", name);
return;
}
ScheduledFuture<?> tracked = scheduledTask.get();
try {
if (ExecutionWrapper.EMPTY != executionWrapper) {
executionWrapper.execute(refreshTask);
Expand All @@ -327,10 +328,8 @@ private void execute() {
} catch (Exception e) {
logger.error("[{}] Error during task execution.", name, e);
} finally {
ScheduledFuture<?> tracked = scheduledTask.get();
if (isDone(tracked)) {
scheduledTask.compareAndSet(tracked, null);
}
// the refresh has finished, even though its scheduler future is not done yet
scheduledTask.compareAndSet(tracked, null);
scheduleNext();
}
}
Expand Down
58 changes: 51 additions & 7 deletions src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.morphix.lang.Holder;
import org.morphix.lang.function.ExecutionWrapper;
import org.morphix.lang.function.LoggerAdapter;
import org.morphix.lang.function.Predicates;
Expand Down Expand Up @@ -653,20 +654,26 @@ void shouldNotScheduleTaskWhenDisabled() {
void shouldSkipExecutionWhenDisabled() {
AtomicInteger counter = new AtomicInteger();

Holder<ReschedulingTask> taskHolder = Holder.empty();

LoggerAdapter logger = mock(LoggerAdapter.class);
doAnswer(invocation -> {
// we disable before the execute is called
return taskHolder.get().disable();
}).when(logger).debug(eq("[{}] Enabling rescheduling task."), any(Object[].class));

ReschedulingTask task = ReschedulingTask.builder()
.name(TASK_NAME)
.scheduler(scheduler())
.task(counter::incrementAndGet)
.nextDelay(() -> DELAY)
.logger(LOGGER)
.logger(logger)
.build();
taskHolder.set(task);

assertThat(task.isDisabled(), is(true));

Method executeTaskMethod = Methods.getOneDeclared("execute", ReschedulingTask.class);
assertThat(executeTaskMethod, is(notNullValue()));

Methods.IgnoreAccess.invoke(executeTaskMethod, task);
task.enable();

assertThat(counter.get(), is(0));
assertThat(task.isScheduled(), is(false));
Expand Down Expand Up @@ -1571,17 +1578,24 @@ void shouldLogWhenNewTaskWasAlreadyScheduledCancellingNotNeeded() throws Excepti
@Test
@SuppressWarnings("resource")
void shouldLogWhenSkippingExecutionBecauseTaskIsDisabled() {
Holder<ReschedulingTask> taskHolder = Holder.empty();

LoggerAdapter logger = mock(LoggerAdapter.class);
doAnswer(invocation -> {
// we disable before the execute is called
return taskHolder.get().disable();
}).when(logger).debug(eq("[{}] Enabling rescheduling task."), any(Object[].class));

ReschedulingTask task = ReschedulingTask.builder()
.name(TASK_NAME)
.scheduler(scheduler())
.task(Runnables.doNothing())
.nextDelay(() -> DELAY)
.logger(logger)
.build();
taskHolder.set(task);

Method executeMethod = Methods.getOneDeclared("execute", ReschedulingTask.class);
Methods.IgnoreAccess.invoke(executeMethod, task);
task.enable();

verify(logger).debug("[{}] Scheduler is disabled, skipping execution.", TASK_NAME);
}
Expand Down Expand Up @@ -1631,6 +1645,36 @@ void shouldLogErrorWhenTaskExecutionFails() {
@Nested
class ConcurrentSchedulingTests {

@Test
@SuppressWarnings("resource")
void shouldNotCancelCurrentFutureDuringNormalRescheduling() {
ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class);
ScheduledFuture<?> first = mock(ScheduledFuture.class);
ScheduledFuture<?> second = mock(ScheduledFuture.class);
AtomicReference<Runnable> callback = new AtomicReference<>();
doAnswer(invocation -> {
callback.set(invocation.getArgument(0));
return first;
}).doReturn(second).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));

ReschedulingTask task = ReschedulingTask.builder()
.scheduler(ScopedResource.unmanaged(scheduledExecutor))
.task(Runnables.doNothing())
.nextDelay(DELAY)
.interruptOnCancel(true)
.build();

task.enable();
callback.get().run();

verify(first, never()).cancel(anyBoolean());
verify(second, never()).cancel(anyBoolean());
assertThat(task.isScheduled(), is(true));

task.disable();
verify(second).cancel(true);
}

@Test
@SuppressWarnings("resource")
void shouldKeepConcurrentEnableWhenPreviousDisableFinishesCancellation() throws Exception {
Expand Down