state = new AtomicReference<>(State.DISABLED);
/**
* Atomic reference to the currently scheduled task. This allows for safe cancellation and rescheduling across threads.
@@ -224,7 +244,7 @@ public String getName() {
}
/**
- * Closes the task, ensuring that any scheduled executions are cancelled and resources are released.
+ * Permanently closes the task, ensuring that any scheduled executions are cancelled and resources are released.
*
* Note: the scheduled task (future) and the scheduler will only be closed if the scheduler is managed by this instance.
*
@@ -232,7 +252,7 @@ public String getName() {
*/
@Override
public void close() throws Exception {
- enabled.set(false);
+ state.set(State.CLOSED);
boolean cancelled = cancelScheduledTask();
scheduler.closeIfManaged(() -> closeRefreshScheduler(cancelled));
}
@@ -307,6 +327,10 @@ 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);
+ }
scheduleNext();
}
}
@@ -326,7 +350,11 @@ private void scheduleNext() {
ScheduledFuture> newTask = executor.schedule(this::execute, delay.toMillis(), TimeUnit.MILLISECONDS);
if (isEnabled()) {
logger.debug("[{}] Scheduled new task: {}.", name, debugInfo(newTask));
- scheduledTask.set(newTask);
+ ScheduledFuture> previous = scheduledTask.getAndSet(newTask);
+ if (null != previous && previous != newTask) {
+ logger.debug("[{}] Replacing previously scheduled task with a new one: cancelling {}.", name, debugInfo(previous));
+ cancel(previous);
+ }
if (isDisabled()) {
logger.debug("[{}] Task was disabled during scheduling.", name);
if (scheduledTask.compareAndSet(newTask, null)) {
@@ -346,9 +374,14 @@ private void scheduleNext() {
* Starts the self-rescheduling task (if not already running).
*
* @return true if the task was started, false if it was already enabled
+ * @throws IllegalStateException if the task has been closed
*/
public boolean enable() {
- if (!enabled.compareAndSet(false, true)) {
+ State previous = state.compareAndExchange(State.DISABLED, State.ENABLED);
+ if (State.CLOSED == previous) {
+ throw new IllegalStateException("Cannot enable a closed rescheduling task");
+ }
+ if (State.ENABLED == previous) {
return false;
}
logger.debug("[{}] Enabling rescheduling task.", name);
@@ -362,7 +395,7 @@ public boolean enable() {
* @return true if the task was disabled, false if it was already disabled
*/
public boolean disable() {
- if (!enabled.compareAndSet(true, false)) {
+ if (!state.compareAndSet(State.ENABLED, State.DISABLED)) {
return false;
}
logger.debug("[{}] Disabling rescheduling task.", name);
@@ -390,7 +423,7 @@ protected String debugInfo(final ScheduledFuture> task) {
* @return true if enabled, false if disabled
*/
public boolean isEnabled() {
- return enabled.get();
+ return State.ENABLED == state.get();
}
/**
@@ -411,6 +444,16 @@ public boolean isScheduled() {
return isNotDone(scheduledTask.get());
}
+ /**
+ * Returns true if there is no pending scheduled execution ({@link #scheduledTask} is null or already done).
+ *
+ * @return true if not scheduled, false if a future is still pending
+ * @see #isScheduled()
+ */
+ public boolean isNotScheduled() {
+ return !isScheduled();
+ }
+
/**
* Returns true if the given task is currently scheduled (not null and not done), false otherwise.
*
diff --git a/src/main/java/org/morphix/lang/thread/Threads.java b/src/main/java/org/morphix/lang/thread/Threads.java
index 4470100c..6ba45fb4 100644
--- a/src/main/java/org/morphix/lang/thread/Threads.java
+++ b/src/main/java/org/morphix/lang/thread/Threads.java
@@ -248,6 +248,29 @@ public static boolean safeJoin(final Thread thread) {
}
}
+ /**
+ * Helper method that calls {@link Thread#join(long)} on the given thread with the given timeout, with
+ * {@link InterruptedException} handling.
+ *
+ * Returns when either the thread terminates or the timeout elapses, whichever comes first. The returned value does not
+ * indicate whether the thread has terminated; check {@link Thread#isAlive()} for that. If the calling thread is
+ * interrupted while waiting, the interrupt status is restored via {@link #handleInterruptedException()}.
+ *
+ * @param thread thread object
+ * @param timeout the maximum time to wait for the thread to terminate
+ * @return true if the join returned normally (the thread terminated or the timeout elapsed), false if the calling
+ * thread was interrupted while waiting
+ */
+ public static boolean safeJoin(final Thread thread, final Duration timeout) {
+ try {
+ thread.join(timeout.toMillis());
+ return true;
+ } catch (InterruptedException e) {
+ handleInterruptedException();
+ return false;
+ }
+ }
+
/**
* Runs each runnable in the list with the given execution type. It only returns after all threads have completed.
* By default, when using: {@code Threads.execute(runnables, ExecutionType.EXECUTOR)} the single thread executor will be
diff --git a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java
index 1049a724..0c91a1f6 100644
--- a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java
+++ b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java
@@ -19,6 +19,7 @@
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
@@ -47,6 +48,7 @@
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
@@ -55,8 +57,11 @@
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import org.morphix.lang.function.ExecutionWrapper;
import org.morphix.lang.function.LoggerAdapter;
+import org.morphix.lang.function.Predicates;
import org.morphix.lang.function.Runnables;
import org.morphix.lang.logging.JulLoggerAdapter;
import org.morphix.lang.resource.ScopedResource;
@@ -593,10 +598,12 @@ void shouldReportScheduledState() throws InterruptedException {
.build();
assertThat(task.isScheduled(), is(false));
+ assertThat(task.isNotScheduled(), is(true));
task.enable();
assertThat(task.isScheduled(), is(true));
+ assertThat(task.isNotScheduled(), is(false));
latch.await(1, TimeUnit.SECONDS);
@@ -605,6 +612,7 @@ void shouldReportScheduledState() throws InterruptedException {
task.disable();
assertThat(task.isScheduled(), is(false));
+ assertThat(task.isNotScheduled(), is(true));
}
@Test
@@ -668,6 +676,70 @@ void shouldSkipExecutionWhenDisabled() {
@Nested
class CloseAndResourceManagementTests {
+ @ParameterizedTest
+ @CsvSource({
+ "true, true",
+ "true, false",
+ "false, true",
+ "false, false"
+ })
+ @SuppressWarnings("resource")
+ void shouldRejectEnableAfterClose(final boolean managed, final boolean initiallyEnabled) throws Exception {
+ Runnable refreshTask = mock(Runnable.class);
+ ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class);
+ ScheduledFuture> scheduledFuture = mock(ScheduledFuture.class);
+ doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ doReturn(true).when(scheduledFuture).cancel(anyBoolean());
+ ScopedResource resource = managed
+ ? ScopedResource.managed(scheduledExecutor)
+ : ScopedResource.unmanaged(scheduledExecutor);
+ ReschedulingTask task = ReschedulingTask.builder()
+ .scheduler(resource)
+ .task(refreshTask)
+ .nextDelay(DELAY)
+ .build();
+ if (initiallyEnabled) {
+ task.enable();
+ }
+
+ task.close();
+
+ assertThrows(IllegalStateException.class, task::enable);
+ assertThat(task.disable(), is(false));
+ task.close();
+ assertThrows(IllegalStateException.class, task::enable);
+ assertThat(task.isEnabled(), is(false));
+ assertThat(task.isDisabled(), is(true));
+ assertThat(task.isScheduled(), is(false));
+ verify(refreshTask, times(initiallyEnabled ? 1 : 0)).run();
+ verify(scheduledExecutor, times(initiallyEnabled ? 1 : 0))
+ .schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldRejectEnableWhileCloseIsCleaningUpEvenIfCleanupFails() {
+ ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class);
+ Runnable refreshTask = mock(Runnable.class);
+ ReschedulingTask task = ReschedulingTask.builder()
+ .scheduler(ScopedResource.managed(scheduledExecutor))
+ .task(refreshTask)
+ .nextDelay(DELAY)
+ .build();
+ IllegalStateException failure = new IllegalStateException("Scheduler cleanup failed");
+ doAnswer(invocation -> {
+ assertThrows(IllegalStateException.class, task::enable);
+ throw failure;
+ }).when(scheduledExecutor).close();
+
+ assertThat(assertThrows(IllegalStateException.class, task::close), is(sameInstance(failure)));
+
+ assertThrows(IllegalStateException.class, task::enable);
+ assertThat(task.isDisabled(), is(true));
+ verify(refreshTask, never()).run();
+ verify(scheduledExecutor, never()).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ }
+
@Test
@SuppressWarnings("resource")
void shouldDisableTaskWhenClosed() throws Exception {
@@ -1033,28 +1105,27 @@ void shouldRescheduleMultipleTimesAndCloseAllFinishedTasks() throws Exception {
task.close();
executor.close();
- // execution 1 (sync) schedules Future 1 (Execution 2).
- // execution 2 runs, schedules Future 2 (Execution 3).
- // execution 3 runs, disable() is called, skips further scheduling.
+ // execution 1 runs on the enable thread and schedules future 1
+ // execution 2 runs on the scheduler thread, schedules future 2, and may cancel future 1 on publish when still pending
+ // execution 3 runs, then disable() cancels the scheduled future and skips further scheduling
assertThat(scheduledFutures.size(), is(executionCount - 1));
- // future 1 completed naturally and should NOT have been explicitly cancelled
- // future 2 was active when disable() was invoked, so it MUST have been cancelled
- // future 3 was never scheduled, so it should not be in the list of scheduled futures at all
- // the order is not guaranteed, but we can check that one future was cancelled and the other was not
- ScheduledFuture> firstFuture = scheduledFutures.stream()
- .filter(f -> !f.isCancelled()) // The one that finished
- .findFirst()
- .orElseThrow();
-
- ScheduledFuture> lastFuture = scheduledFutures.stream()
+ // 1. both futures are spied instances returned from executor.schedule(...)
+ // 2. publishing a newer future or calling disable() cancels an older one, so at least one must be marked cancelled
+ // 3. any future not marked cancelled must not have had cancel() called on it by the task
+ ScheduledFuture> cancelledFuture = scheduledFutures.stream()
.filter(Future::isCancelled)
.findFirst()
- .orElseThrow();
-
- // Now verify regardless of insertion order
- verify(firstFuture, never()).cancel(anyBoolean());
- verify(lastFuture, atLeastOnce()).cancel(anyBoolean());
+ .orElse(null);
+ assertNotNull(cancelledFuture);
+ verify(cancelledFuture, atLeastOnce()).cancel(anyBoolean());
+
+ List> notCancelledFutures = scheduledFutures.stream()
+ .filter(Predicates.not(Future::isCancelled))
+ .toList();
+ for (ScheduledFuture> notCancelledFuture : notCancelledFutures) {
+ verify(notCancelledFuture, never()).cancel(anyBoolean());
+ }
assertThat(completed, is(true));
assertThat(counter.get(), equalTo(executionCount));
@@ -1109,9 +1180,8 @@ void shouldCancelTaskIfDisabledAfterSettingReference() throws Exception {
continueScheduling.countDown();
cancelAttempted.await(5, TimeUnit.SECONDS);
- verify(spyLogger, timeout(1000)).debug(
- startsWith("[{}] Cancelling orphaned task."),
- eq("test-task"));
+ verify(spyLogger, timeout(1000)).debug("[{}] Task was disabled during scheduling.", "test-task");
+ verify(spyLogger, timeout(1000)).debug(startsWith("[{}] Cancelling orphaned task."), eq("test-task"));
verify(mockFuture).cancel(anyBoolean());
}
@@ -1180,7 +1250,7 @@ void shouldNotCancelTaskIfEnabledBackAfterDisabled() throws Exception {
task.close();
verify(spyLogger, timeout(1000)).debug("[{}] New task was already scheduled, cancelling not needed.", TASK_NAME);
- verify(mockFuture1, never()).cancel(anyBoolean());
+ // a later publish may still supersede and cancel the earlier scheduled future
verify(mockFuture2).cancel(anyBoolean());
}
}
@@ -1334,5 +1404,532 @@ void shouldEnableAndDisableTaskAndLogExecution() throws InterruptedException {
verify(logger, atLeast(executionCount - 1)).debug("[{}] Scheduling next execution in {}ms.", TASK_NAME, DELAY.toMillis());
verify(logger).debug("[{}] Disabling rescheduling task.", TASK_NAME);
}
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldLogWhenCancellingScheduledTask() {
+ ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class);
+ ScheduledFuture> scheduledFuture = mock(ScheduledFuture.class);
+ doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ doReturn(true).when(scheduledFuture).cancel(anyBoolean());
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(ScopedResource.unmanaged(scheduledExecutor))
+ .task(Runnables.doNothing())
+ .nextDelay(() -> Duration.ofSeconds(5))
+ .logger(logger)
+ .build();
+
+ task.enable();
+ task.disable();
+
+ verify(logger).debug(eq("[{}] Scheduled new task: {}."), eq(TASK_NAME), any());
+ verify(logger).debug(eq("[{}] Called cancel scheduled task: {}."), eq(TASK_NAME), any());
+ verify(logger).debug(eq("[{}] Attempting to cancel scheduled task: {}."), eq(TASK_NAME), any());
+ verify(scheduledFuture).cancel(anyBoolean());
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldLogScheduledNewTaskWhenNextExecutionIsScheduled() {
+ ScheduledFuture> scheduledFuture = mock(ScheduledFuture.class);
+ ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class);
+ doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(ScopedResource.unmanaged(scheduledExecutor))
+ .task(Runnables.doNothing())
+ .nextDelay(() -> Duration.ofSeconds(5))
+ .logger(logger)
+ .build();
+
+ task.enable();
+
+ verify(logger).debug("[{}] Scheduling next execution in {}ms.", TASK_NAME, Duration.ofSeconds(5).toMillis());
+ verify(logger).debug(eq("[{}] Scheduled new task: {}."), eq(TASK_NAME), any());
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldLogWhenReplacingPreviouslyScheduledTaskWithNewOne() {
+ ScheduledFuture> future1 = mock(ScheduledFuture.class);
+ ScheduledFuture> future2 = mock(ScheduledFuture.class);
+ doReturn(true).when(future1).cancel(anyBoolean());
+ doReturn(false).when(future1).isDone();
+ ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class);
+ doReturn(future1).doReturn(future2).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any());
+
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(ScopedResource.unmanaged(scheduledExecutor))
+ .task(Runnables.doNothing())
+ .nextDelay(() -> Duration.ofSeconds(5))
+ .logger(logger)
+ .build();
+
+ task.enable();
+
+ Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class);
+ Methods.IgnoreAccess.invoke(scheduleNextMethod, task);
+
+ verify(logger).debug(eq("[{}] Replacing previously scheduled task with a new one: cancelling {}."), eq(TASK_NAME),
+ any());
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldLogWhenTaskWasDisabledDuringSchedulingAndOrphanIsCancelled() throws Exception {
+ CountDownLatch taskIsSet = new CountDownLatch(1);
+ CountDownLatch continueScheduling = new CountDownLatch(1);
+
+ ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class);
+ ScheduledFuture> mockFuture = mock(ScheduledFuture.class);
+ doReturn(true).when(mockFuture).cancel(anyBoolean());
+ doReturn(mockFuture).when(mockExecutor).schedule(any(Runnable.class), anyLong(), any());
+
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ doAnswer(invocation -> {
+ taskIsSet.countDown();
+ continueScheduling.await();
+ return null;
+ }).when(logger).debug(startsWith("[{}] Scheduled new task"), any(), any());
+
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(ScopedResource.unmanaged(mockExecutor))
+ .task(Runnables.doNothing())
+ .nextDelay(Duration.ofMillis(500))
+ .logger(logger)
+ .build();
+
+ Thread.ofVirtual().start(task::enable);
+ taskIsSet.await(5, TimeUnit.SECONDS);
+ task.disable();
+ continueScheduling.countDown();
+
+ verify(logger, timeout(1000)).debug("[{}] Task was disabled during scheduling.", TASK_NAME);
+ verify(logger, timeout(1000)).debug(startsWith("[{}] Cancelling orphaned task."), eq(TASK_NAME));
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldLogWhenNewTaskWasAlreadyScheduledCancellingNotNeeded() throws Exception {
+ CountDownLatch firstTaskIsSet = new CountDownLatch(1);
+ CountDownLatch secondTaskIsSet = new CountDownLatch(1);
+ CountDownLatch continueScheduling = new CountDownLatch(1);
+ CountDownLatch disableCalled = new CountDownLatch(1);
+ CountDownLatch enableCalled = new CountDownLatch(1);
+
+ ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class);
+ ScheduledFuture> mockFuture1 = mock(ScheduledFuture.class);
+ ScheduledFuture> mockFuture2 = mock(ScheduledFuture.class);
+ doReturn(mockFuture1).doReturn(mockFuture2).when(mockExecutor).schedule(any(Runnable.class), anyLong(), any());
+
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ doAnswer(invocation -> {
+ if (firstTaskIsSet.getCount() > 0) {
+ firstTaskIsSet.countDown();
+ } else {
+ secondTaskIsSet.countDown();
+ }
+ continueScheduling.await();
+ return null;
+ }).when(logger).debug(startsWith("[{}] Scheduled new task"), any(), any());
+ doAnswer(invocation -> {
+ disableCalled.countDown();
+ enableCalled.await();
+ return null;
+ }).when(logger).debug(startsWith("[{}] Task was disabled during scheduling"), any());
+
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(ScopedResource.unmanaged(mockExecutor))
+ .task(Runnables.doNothing())
+ .nextDelay(Duration.ofMillis(500))
+ .logger(logger)
+ .build();
+
+ Thread.ofVirtual().start(task::enable);
+ firstTaskIsSet.await(5, TimeUnit.SECONDS);
+ task.disable();
+ continueScheduling.countDown();
+ disableCalled.await(5, TimeUnit.SECONDS);
+ task.enable();
+ secondTaskIsSet.await(5, TimeUnit.SECONDS);
+ enableCalled.countDown();
+ task.close();
+
+ verify(logger, timeout(1000)).debug("[{}] Task was disabled during scheduling.", TASK_NAME);
+ verify(logger, timeout(1000)).debug("[{}] New task was already scheduled, cancelling not needed.", TASK_NAME);
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldLogWhenSkippingExecutionBecauseTaskIsDisabled() {
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(scheduler())
+ .task(Runnables.doNothing())
+ .nextDelay(() -> DELAY)
+ .logger(logger)
+ .build();
+
+ Method executeMethod = Methods.getOneDeclared("execute", ReschedulingTask.class);
+ Methods.IgnoreAccess.invoke(executeMethod, task);
+
+ verify(logger).debug("[{}] Scheduler is disabled, skipping execution.", TASK_NAME);
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldLogWhenSkippingSchedulingBecauseTaskIsDisabled() {
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(scheduler())
+ .task(Runnables.doNothing())
+ .nextDelay(() -> DELAY)
+ .logger(logger)
+ .build();
+
+ Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class);
+ Methods.IgnoreAccess.invoke(scheduleNextMethod, task);
+
+ verify(logger).debug("[{}] Scheduler is disabled, skipping scheduling next execution.", TASK_NAME);
+ assertThat(task.isScheduled(), is(false));
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldLogErrorWhenTaskExecutionFails() {
+ IllegalStateException exception = new IllegalStateException("test failure");
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(scheduler())
+ .task(() -> {
+ throw exception;
+ })
+ .nextDelay(() -> Duration.ofHours(1))
+ .logger(logger)
+ .build();
+
+ task.enable();
+ task.disable();
+
+ verify(logger).error("[{}] Error during task execution.", TASK_NAME, exception);
+ }
+
+ }
+
+ @Nested
+ class ConcurrentSchedulingTests {
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldKeepConcurrentEnableWhenPreviousDisableFinishesCancellation() throws Exception {
+ CountDownLatch cancellationStarted = new CountDownLatch(1);
+ CountDownLatch finishCancellation = new CountDownLatch(1);
+ CountDownLatch refreshStarted = new CountDownLatch(1);
+ CountDownLatch finishRefresh = new CountDownLatch(1);
+
+ ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class);
+ ScheduledFuture> firstFuture = mock(ScheduledFuture.class);
+ ScheduledFuture> nextFuture = mock(ScheduledFuture.class);
+ doReturn(firstFuture).doReturn(nextFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ doAnswer(invocation -> {
+ cancellationStarted.countDown();
+ assertThat(finishCancellation.await(5, TimeUnit.SECONDS), is(true));
+ return true;
+ }).when(firstFuture).cancel(anyBoolean());
+ AtomicInteger executions = new AtomicInteger();
+ Runnable refresh = mock(Runnable.class);
+ doAnswer(invocation -> {
+ if (executions.incrementAndGet() == 2) {
+ refreshStarted.countDown();
+ assertThat(finishRefresh.await(5, TimeUnit.SECONDS), is(true));
+ }
+ return null;
+ }).when(refresh).run();
+
+ ReschedulingTask task = ReschedulingTask.builder()
+ .scheduler(ScopedResource.unmanaged(scheduledExecutor))
+ .task(refresh)
+ .nextDelay(Duration.ofHours(1))
+ .build();
+
+ try (task; var workers = Executors.newVirtualThreadPerTaskExecutor()) {
+ try {
+ task.enable();
+ Future disabling = workers.submit(task::disable);
+ assertThat(cancellationStarted.await(5, TimeUnit.SECONDS), is(true));
+ Future enabling = workers.submit(task::enable);
+ assertThat(refreshStarted.await(5, TimeUnit.SECONDS), is(true));
+
+ // finish the earlier disable while the new enable is still executing its initial refresh
+ finishCancellation.countDown();
+ assertThat(disabling.get(5, TimeUnit.SECONDS), is(true));
+ finishRefresh.countDown();
+ assertThat(enabling.get(5, TimeUnit.SECONDS), is(true));
+
+ assertThat(task.isEnabled(), is(true));
+ assertThat(task.isScheduled(), is(true));
+ verify(scheduledExecutor, times(2)).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ verify(nextFuture, never()).cancel(anyBoolean());
+ } finally {
+ finishCancellation.countDown();
+ finishRefresh.countDown();
+ }
+ }
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldCancelPreviouslyPublishedFutureWhenReschedulingWhileAnotherIsPending() {
+ ScheduledFuture> future1 = mock(ScheduledFuture.class);
+ ScheduledFuture> future2 = mock(ScheduledFuture.class);
+ doReturn(true).when(future1).cancel(anyBoolean());
+ doReturn(true).when(future2).cancel(anyBoolean());
+ doReturn(false).when(future1).isDone();
+ ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class);
+ doReturn(future1).doReturn(future2).when(mockExecutor).schedule(any(Runnable.class), anyLong(), any());
+
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(ScopedResource.unmanaged(mockExecutor))
+ .task(Runnables.doNothing())
+ .nextDelay(Duration.ofSeconds(5))
+ .build();
+
+ task.enable();
+
+ Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class);
+ Methods.IgnoreAccess.invoke(scheduleNextMethod, task);
+
+ verify(future1).cancel(anyBoolean());
+ verify(future2, never()).cancel(anyBoolean());
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldNotCancelScheduledTaskWhenReplacingWithTheSameFutureReference() {
+ ScheduledFuture> future = mock(ScheduledFuture.class);
+ ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class);
+ doReturn(future).when(mockExecutor).schedule(any(Runnable.class), anyLong(), any());
+
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(ScopedResource.unmanaged(mockExecutor))
+ .task(Runnables.doNothing())
+ .nextDelay(Duration.ofSeconds(5))
+ .build();
+
+ task.enable();
+
+ Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class);
+ Methods.IgnoreAccess.invoke(scheduleNextMethod, task);
+
+ verify(future, never()).cancel(anyBoolean());
+ }
+ }
+
+ @Nested
+ class SchedulingWhileDisabledTests {
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldCancelAndLogWhenTaskIsDisabledWhileSchedulingNext() {
+ ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class);
+ ScheduledFuture> scheduledFuture = mock(ScheduledFuture.class);
+ doReturn(true).when(scheduledFuture).cancel(anyBoolean());
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ AtomicReference taskReference = new AtomicReference<>();
+ // disable the task right after the check at the beginning of scheduleNext
+ doAnswer(invocation -> {
+ taskReference.get().disable();
+ return scheduledFuture;
+ }).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(ScopedResource.unmanaged(scheduledExecutor))
+ .task(Runnables.doNothing())
+ .nextDelay(() -> Duration.ofSeconds(5))
+ .logger(logger)
+ .build();
+ taskReference.set(task);
+
+ task.enable();
+
+ verify(logger).debug("[{}] Task was disabled during scheduling. Cancelling immediate orphan.", TASK_NAME);
+ verify(scheduledFuture).cancel(anyBoolean());
+ assertThat(task.isScheduled(), is(false));
+ }
+ }
+
+ @Nested
+ class ExecutionWrapperInvocationTests {
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldRunTaskThroughExecutionWrapper() {
+ AtomicInteger wrapperCounter = new AtomicInteger();
+ AtomicInteger executionCounter = new AtomicInteger();
+
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(scheduler())
+ .task(executionCounter::incrementAndGet)
+ .wrap(wrapped -> () -> {
+ wrapperCounter.incrementAndGet();
+ return wrapped.get();
+ })
+ .nextDelay(() -> Duration.ofHours(1))
+ .build();
+
+ task.enable();
+ task.disable();
+
+ assertThat(wrapperCounter.get(), is(1));
+ assertThat(executionCounter.get(), is(1));
+ }
+ }
+
+ @Nested
+ class CancellationOutcomeTests {
+
+ private final ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class);
+ private final ScheduledFuture> scheduledFuture = mock(ScheduledFuture.class);
+
+ @SuppressWarnings("resource")
+ private ReschedulingTask managedTask(final LoggerAdapter logger) {
+ doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ return ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(ScopedResource.managed(scheduledExecutor))
+ .task(Runnables.doNothing())
+ .nextDelay(() -> Duration.ofSeconds(5))
+ .logger(logger)
+ .build();
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldCloseSchedulerGracefullyWhenCancellationSucceeds() throws Exception {
+ doReturn(true).when(scheduledFuture).cancel(anyBoolean());
+ ReschedulingTask task = managedTask(LoggerAdapter.none());
+
+ task.enable();
+ task.close();
+
+ verify(scheduledFuture).cancel(anyBoolean());
+ verify(scheduledExecutor).close();
+ verify(scheduledExecutor, never()).shutdownNow();
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldCloseSchedulerGracefullyWhenThereIsNoScheduledTask() throws Exception {
+ ReschedulingTask task = managedTask(LoggerAdapter.none());
+
+ task.close();
+
+ verify(scheduledExecutor).close();
+ verify(scheduledExecutor, never()).shutdownNow();
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldCloseSchedulerGracefullyWhenScheduledTaskIsAlreadyDone() throws Exception {
+ doReturn(true).when(scheduledFuture).isDone();
+ ReschedulingTask task = managedTask(LoggerAdapter.none());
+
+ task.enable();
+ task.close();
+
+ verify(scheduledFuture, never()).cancel(anyBoolean());
+ verify(scheduledExecutor).close();
+ verify(scheduledExecutor, never()).shutdownNow();
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldShutdownSchedulerNowAndLogRemainingTasksWhenCancellationFails() throws Exception {
+ doReturn(false).when(scheduledFuture).cancel(anyBoolean());
+ doReturn(List.of(mock(Runnable.class))).when(scheduledExecutor).shutdownNow();
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ ReschedulingTask task = managedTask(logger);
+
+ task.enable();
+ task.close();
+
+ verify(scheduledExecutor).shutdownNow();
+ verify(scheduledExecutor, never()).close();
+ verify(logger).warn("[{}] Scheduler closed with {} remaining tasks.", TASK_NAME, 1);
+ }
+ }
+
+ @Nested
+ class DebugInfoTests {
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldReturnNotAvailableWhenDebugIsDisabled() {
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ doReturn(true).when(logger).isDisabled(LoggerAdapter.LoggingLevel.DEBUG);
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(scheduler())
+ .task(Runnables.doNothing())
+ .nextDelay(() -> DELAY)
+ .logger(logger)
+ .build();
+
+ String info = task.debugInfo(mock(ScheduledFuture.class));
+
+ assertThat(info, equalTo("N/A"));
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldReturnHashCodeAndStateWhenDebugIsEnabled() {
+ ScopedResource scheduler = scheduler();
+ ScheduledFuture> future = scheduler.unwrap().schedule(Runnables.doNothing(), 1, TimeUnit.HOURS);
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(scheduler)
+ .task(Runnables.doNothing())
+ .nextDelay(() -> DELAY)
+ .logger(logger)
+ .build();
+
+ String info = task.debugInfo(future);
+
+ assertThat(info, equalTo("hashCode:[" + future.hashCode() + "], state:[" + future.state() + "]"));
+ }
+
+ @Test
+ @SuppressWarnings("resource")
+ void shouldReturnNullValuesWhenDebugIsEnabledAndTaskIsNull() {
+ LoggerAdapter logger = mock(LoggerAdapter.class);
+ ReschedulingTask task = ReschedulingTask.builder()
+ .name(TASK_NAME)
+ .scheduler(scheduler())
+ .task(Runnables.doNothing())
+ .nextDelay(() -> DELAY)
+ .logger(logger)
+ .build();
+
+ String info = task.debugInfo(null);
+
+ assertThat(info, equalTo("hashCode:[null], state:[null]"));
+ }
}
}
diff --git a/src/test/java/org/morphix/lang/thread/StackedContextHolderTest.java b/src/test/java/org/morphix/lang/thread/StackedContextHolderTest.java
index 23c93451..99cb5434 100644
--- a/src/test/java/org/morphix/lang/thread/StackedContextHolderTest.java
+++ b/src/test/java/org/morphix/lang/thread/StackedContextHolderTest.java
@@ -209,6 +209,53 @@ void shouldNotChangeTenantIdWhenStackIsEmpty() {
assertThat(TenantContextHolder.getTenantId(), equalTo(null));
}
+ @Test
+ void shouldSetFunctionAndRemoveElementAroundFunctionCall() {
+ List calls = new ArrayList<>();
+
+ String result = StackedContextHolder.on(TENANT_ID,
+ element -> calls.add("set:" + element),
+ element -> calls.add("remove:" + element),
+ (String arg) -> {
+ calls.add("run:" + arg);
+ return arg;
+ },
+ TEST_STRING);
+
+ assertThat(result, equalTo(TEST_STRING));
+ assertThat(calls, equalTo(List.of("set:" + TENANT_ID, "run:" + TEST_STRING, "remove:" + TENANT_ID)));
+ }
+
+ @Test
+ void shouldRemoveElementWhenFunctionThrows() {
+ List calls = new ArrayList<>();
+
+ assertThrows(IllegalStateException.class, () -> StackedContextHolder.on(TENANT_ID,
+ element -> calls.add("set:" + element),
+ element -> calls.add("remove:" + element),
+ (String arg) -> {
+ throw new IllegalStateException();
+ },
+ TEST_STRING));
+
+ assertThat(calls, equalTo(List.of("set:" + TENANT_ID, "remove:" + TENANT_ID)));
+ }
+
+ @Test
+ void shouldClearThreadStackWhenRemovingElementFromEmptyStack() {
+ int removeCallsBefore = DummyTenantContextHolder.stack.removeCalls;
+
+ try {
+ DummyTenantContextHolder.INSTANCE.clearElement();
+
+ assertThat(DummyTenantContextHolder.stack.removeCalls, equalTo(removeCallsBefore + 1));
+ assertThat(DummyTenantContextHolder.getTenantId(), equalTo(null));
+ } finally {
+ // restore the shared counter so other tests asserting on it are not affected by execution order
+ DummyTenantContextHolder.stack.removeCalls = removeCallsBefore;
+ }
+ }
+
@Test
void shouldClearManuallySetTenantId() {
DummyTenantContextHolder.INSTANCE.setElement(TENANT_ID);
diff --git a/src/test/java/org/morphix/lang/thread/SynchronizedTest.java b/src/test/java/org/morphix/lang/thread/SynchronizedTest.java
index 32e7ef65..8236940f 100644
--- a/src/test/java/org/morphix/lang/thread/SynchronizedTest.java
+++ b/src/test/java/org/morphix/lang/thread/SynchronizedTest.java
@@ -115,6 +115,59 @@ void shouldTryRunnableWithTimeout() throws InterruptedException {
});
}
+ @Test
+ void shouldReleaseLockAfterTrySupplier() {
+ ReentrantLock lock = new ReentrantLock();
+
+ assertThat(Synchronized.tryWith(lock, 1, TimeUnit.SECONDS, () -> VALUE, () -> DEFAULT), equalTo(VALUE));
+
+ assertFalse(lock.isLocked());
+ }
+
+ @Test
+ void shouldReleaseLockAfterTrySupplierThrows() {
+ ReentrantLock lock = new ReentrantLock();
+
+ assertThrows(IllegalStateException.class, () -> Synchronized.tryWith(lock, 1, TimeUnit.SECONDS, () -> {
+ throw new IllegalStateException();
+ }));
+
+ assertFalse(lock.isLocked());
+ }
+
+ @Test
+ void shouldReleaseLockAfterTryRunnable() {
+ ReentrantLock lock = new ReentrantLock();
+
+ Synchronized.tryWith(lock, 1, TimeUnit.SECONDS, () -> {
+ // nothing to do
+ });
+
+ assertFalse(lock.isLocked());
+ }
+
+ @Test
+ void shouldRunRunnableWithDurationTimeout() {
+ ReentrantLock lock = new ReentrantLock();
+ AtomicBoolean ran = new AtomicBoolean();
+
+ Synchronized.tryWith(lock, Duration.ofSeconds(1), () -> ran.set(true));
+
+ assertTrue(ran.get());
+ assertFalse(lock.isLocked());
+ }
+
+ @Test
+ void shouldRunRunnableWithDefaultTimeout() {
+ ReentrantLock lock = new ReentrantLock();
+ AtomicBoolean ran = new AtomicBoolean();
+
+ Synchronized.tryWith(lock, () -> ran.set(true));
+
+ assertTrue(ran.get());
+ assertFalse(lock.isLocked());
+ }
+
@Test
void shouldReturnDefaultWhenInterrupted() throws InterruptedException {
ReentrantLock lock = new ReentrantLock();
diff --git a/src/test/java/org/morphix/lang/thread/ThreadsTest.java b/src/test/java/org/morphix/lang/thread/ThreadsTest.java
index 3330d8c2..89f004f4 100644
--- a/src/test/java/org/morphix/lang/thread/ThreadsTest.java
+++ b/src/test/java/org/morphix/lang/thread/ThreadsTest.java
@@ -21,10 +21,16 @@
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@@ -34,6 +40,8 @@
import java.util.List;
import java.util.Queue;
import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
@@ -249,6 +257,45 @@ void shouldNotThrowExeptionOnTimeoutWhenRunningSupplierWithTimeout() {
void shouldNotThrowExeptionOnTimeoutWhenRunningRunnableWithTimeout() {
assertDoesNotThrow(() -> Threads.execute(Duration.ofSeconds(10), Runnables.doNothing()));
}
+
+ @Test
+ @SuppressWarnings({ "unchecked", "resource" })
+ void shouldCancelTaskWhenExecutionFails() throws Exception {
+ Future task = mock(Future.class);
+ doThrow(new TimeoutException()).when(task).get(anyLong(), any(TimeUnit.class));
+ ExecutorService executor = mock(ExecutorService.class);
+ doReturn(task).when(executor).submit(any(Callable.class));
+
+ try (MockedStatic executors = Mockito.mockStatic(Executors.class)) {
+ executors.when(Executors::newVirtualThreadPerTaskExecutor).thenReturn(executor);
+
+ assertThrows(TimeoutException.class, () -> Threads.execute(Duration.ofSeconds(10), () -> TEST_STRING));
+
+ verify(task).cancel(true);
+ verify(executor).shutdownNow();
+ }
+ }
+
+ @Test
+ @SuppressWarnings({ "unchecked", "resource" })
+ void shouldRestoreInterruptedStatusWhenInterruptedWhileWaitingForTaskTermination() throws InterruptedException {
+ ExecutorService executor = mock(ExecutorService.class);
+ doReturn(CompletableFuture.completedFuture(TEST_STRING)).when(executor).submit(any(Callable.class));
+ doThrow(new InterruptedException()).when(executor).awaitTermination(anyLong(), any(TimeUnit.class));
+
+ try (MockedStatic executors = Mockito.mockStatic(Executors.class)) {
+ executors.when(Executors::newVirtualThreadPerTaskExecutor).thenReturn(executor);
+
+ String result = Threads.execute(Duration.ofSeconds(10), () -> TEST_STRING);
+
+ assertThat(result, equalTo(TEST_STRING));
+ verify(executor).shutdownNow();
+ assertTrue(Thread.currentThread().isInterrupted());
+ } finally {
+ // clear the interrupted flag so it does not leak into other tests
+ Thread.interrupted();
+ }
+ }
}
@Nested
@@ -405,6 +452,117 @@ void shouldSafelyWaitForCountdownLatchWithDurationAndHandleInterruptedExceptionO
assertFalse(countReached.get());
assertFalse(result);
}
+
+ @Test
+ void shouldRestoreInterruptedStatusWhenSafeWaitIsInterrupted() {
+ CountDownLatch latch = new CountDownLatch(1);
+
+ try {
+ Thread.currentThread().interrupt();
+ Threads.safeWait(latch);
+
+ assertTrue(Thread.currentThread().isInterrupted());
+ } finally {
+ // clear the interrupted flag so it does not leak into other tests
+ Thread.interrupted();
+ }
+ }
+
+ @Test
+ void shouldReturnFalseWhenSafeWaitWithDurationTimesOut() {
+ CountDownLatch latch = new CountDownLatch(1);
+
+ boolean result = Threads.safeWait(latch, Duration.ofMillis(10));
+
+ assertFalse(result);
+ assertFalse(Thread.currentThread().isInterrupted());
+ }
+
+ @Test
+ void shouldRestoreInterruptedStatusWhenSafeWaitWithDurationIsInterrupted() {
+ CountDownLatch latch = new CountDownLatch(1);
+
+ try {
+ Thread.currentThread().interrupt();
+ boolean result = Threads.safeWait(latch, Duration.ofSeconds(10));
+
+ assertFalse(result);
+ assertTrue(Thread.currentThread().isInterrupted());
+ } finally {
+ // clear the interrupted flag so it does not leak into other tests
+ Thread.interrupted();
+ }
+ }
+
+ @Test
+ void shouldRestoreInterruptedStatusWhenSafeJoinIsInterrupted() {
+ CountDownLatch latch = new CountDownLatch(1);
+ Thread thread = Thread.ofPlatform().start(() -> Threads.safeWait(latch));
+
+ try {
+ // interrupt the joining thread not the thread being joined
+ Thread.currentThread().interrupt();
+ boolean result = Threads.safeJoin(thread);
+
+ assertFalse(result);
+ assertTrue(Thread.currentThread().isInterrupted());
+ assertTrue(thread.isAlive());
+ } finally {
+ // clear the interrupted flag so it does not leak into other tests
+ Thread.interrupted();
+ latch.countDown();
+ Threads.safeJoin(thread);
+ }
+ }
+
+ @Test
+ void shouldSafelyJoinWithTimeoutWhenThreadTerminatesBeforeTimeout() {
+ AtomicBoolean ran = new AtomicBoolean(false);
+ Thread thread = Thread.ofPlatform().start(() -> ran.set(true));
+
+ boolean result = Threads.safeJoin(thread, Duration.ofSeconds(10));
+
+ assertTrue(result);
+ assertTrue(ran.get());
+ assertFalse(thread.isAlive());
+ }
+
+ @Test
+ void shouldSafelyJoinWithTimeoutAndReturnTrueWhenTimeoutElapsesAndThreadIsStillAlive() {
+ CountDownLatch latch = new CountDownLatch(1);
+ Thread thread = Thread.ofPlatform().start(() -> Threads.safeWait(latch));
+
+ try {
+ boolean result = Threads.safeJoin(thread, Duration.ofMillis(10));
+
+ assertTrue(result);
+ assertTrue(thread.isAlive());
+ } finally {
+ latch.countDown();
+ Threads.safeJoin(thread);
+ }
+ }
+
+ @Test
+ void shouldSafelyJoinWithTimeoutAndHandleInterruptedException() {
+ CountDownLatch latch = new CountDownLatch(1);
+ Thread thread = Thread.ofPlatform().start(() -> Threads.safeWait(latch));
+
+ try {
+ // interrupt the joining thread not the thread being joined
+ Thread.currentThread().interrupt();
+ boolean result = Threads.safeJoin(thread, Duration.ofSeconds(10));
+
+ assertFalse(result);
+ assertTrue(Thread.currentThread().isInterrupted());
+ assertTrue(thread.isAlive());
+ } finally {
+ // clear the interrupted flag so it does not leak into other tests
+ Thread.interrupted();
+ latch.countDown();
+ Threads.safeJoin(thread);
+ }
+ }
}
@Nested
@@ -572,6 +730,66 @@ void shouldNotWaitForTimeoutIfInterrupted() {
assertFalse(condition.get());
}
+
+ @Test
+ @Timeout(5)
+ void shouldReturnTrueWhenConditionIsMet() {
+ AtomicInteger checks = new AtomicInteger(0);
+
+ boolean result = Threads.waitUntil(() -> checks.incrementAndGet() >= 3);
+
+ assertTrue(result);
+ }
+
+ @Test
+ @Timeout(5)
+ void shouldReturnFalseWhenInterruptedWhileWaitingWithoutTimeout() {
+ try {
+ Thread.currentThread().interrupt();
+ boolean result = Threads.waitUntil(() -> false);
+
+ assertFalse(result);
+ } finally {
+ // clear the interrupted flag so it does not leak into other tests
+ Thread.interrupted();
+ }
+ }
+
+ @Test
+ @Timeout(5)
+ void shouldReturnTrueWhenConditionIsMetWithinTimeout() {
+ AtomicInteger checks = new AtomicInteger(0);
+
+ boolean result = Threads.waitUntil(() -> checks.incrementAndGet() >= 3, Duration.ofSeconds(3));
+
+ assertTrue(result);
+ }
+
+ @Test
+ @Timeout(5)
+ void shouldReturnFalseWhenConditionIsNotMetWithinTimeout() {
+ boolean result = Threads.waitUntil(() -> false, Duration.ofMillis(20));
+
+ assertFalse(result);
+ }
+
+ @Test
+ @Timeout(5)
+ void shouldReturnTrueWhenConditionIsMetWithinTimeoutAndPollInterval() {
+ AtomicInteger checks = new AtomicInteger(0);
+
+ boolean result = Threads.waitUntil(() -> checks.incrementAndGet() >= 3, Duration.ofSeconds(3), Duration.ofMillis(1));
+
+ assertTrue(result);
+ }
+
+ @Test
+ @Timeout(5)
+ void shouldReturnFalseWhenConditionIsNotMetWithinTimeoutAndPollInterval() {
+ boolean result = Threads.waitUntil(() -> false, Duration.ofMillis(20), Duration.ofMillis(1));
+
+ assertFalse(result);
+ }
}
@Nested
@@ -658,6 +876,53 @@ void shouldExecuteThrottledWithExecutorAsAlias() {
assertThat(executions.get(), equalTo(THREAD_COUNT));
}
+
+ @Test
+ void shouldNotWaitForIntervalAfterLastBatch() {
+ AtomicInteger executions = new AtomicInteger(0);
+ List runnables = IntStream.range(0, 4)
+ .mapToObj(i -> (Runnable) executions::incrementAndGet)
+ .toList();
+
+ // a single batch (exactly threadCount items) must not wait for the interval
+ assertTimeoutPreemptively(Duration.ofSeconds(2),
+ () -> Threads.execute(runnables, 4, Duration.ofSeconds(30), ExecutionType.SEQUENTIAL));
+
+ assertThat(executions.get(), equalTo(4));
+ }
+
+ @Test
+ void shouldExecuteExactBatchesWithoutEmptyBatch() {
+ List runnables = IntStream.range(0, 4)
+ .mapToObj(i -> (Runnable) new AtomicInteger(i)::incrementAndGet)
+ .toList();
+ Executor executor = Runnable::run;
+
+ try (MockedStatic threadsMock = Mockito.mockStatic(Threads.class, Mockito.CALLS_REAL_METHODS)) {
+ Threads.execute(runnables, 2, Duration.ofMillis(1), executor);
+
+ threadsMock.verify(() -> Threads.execute(runnables.subList(0, 2), executor));
+ threadsMock.verify(() -> Threads.execute(runnables.subList(2, 4), executor));
+ threadsMock.verify(() -> Threads.execute(anyList(), eq(executor)), times(2));
+ }
+ }
+
+ @Test
+ void shouldExecuteLastPartialBatch() {
+ List runnables = IntStream.range(0, 5)
+ .mapToObj(i -> (Runnable) new AtomicInteger(i)::incrementAndGet)
+ .toList();
+ Executor executor = Runnable::run;
+
+ try (MockedStatic threadsMock = Mockito.mockStatic(Threads.class, Mockito.CALLS_REAL_METHODS)) {
+ Threads.execute(runnables, 2, Duration.ofMillis(1), executor);
+
+ threadsMock.verify(() -> Threads.execute(runnables.subList(0, 2), executor));
+ threadsMock.verify(() -> Threads.execute(runnables.subList(2, 4), executor));
+ threadsMock.verify(() -> Threads.execute(runnables.subList(4, 5), executor));
+ threadsMock.verify(() -> Threads.execute(anyList(), eq(executor)), times(3));
+ }
+ }
}
@Nested
diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java
index 046db0e9..baa3f30e 100644
--- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java
+++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java
@@ -140,6 +140,20 @@ void shouldSkipNullPathInVarargs() {
assertThat(result, equalTo("Alice"));
}
+ @Test
+ void shouldReturnNullWhenObjectIsNullOnCommaSeparatedPaths() {
+ var result = Fields.Safe.getByPaths(null, "person.name");
+
+ assertThat(result, nullValue());
+ }
+
+ @Test
+ void shouldReturnNullWhenObjectIsNullOnVarargs() {
+ var result = Fields.Safe.getByPaths(null, "unknown", "person.name");
+
+ assertThat(result, nullValue());
+ }
+
@Test
void shouldReturnNullWhenPathsArrayIsNull() {
var result = Fields.Safe.getByPaths(data, (String[]) null);
diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetTest.java
index 3013ea8c..308d7aa0 100644
--- a/src/test/java/org/morphix/reflection/FieldsSafeGetTest.java
+++ b/src/test/java/org/morphix/reflection/FieldsSafeGetTest.java
@@ -207,6 +207,13 @@ void shouldReturnNullIfObjectFieldNameIsNull() {
assertThat(result, equalTo(null));
}
+ @Test
+ void shouldReturnNullIfObjectIsNullOnCallWithFieldName() {
+ Object result = Fields.Safe.get(null, "s");
+
+ assertThat(result, equalTo(null));
+ }
+
@Test
void shouldReturnClassClassloaderField() {
Class> clazz = Class.class;