From 677dbedeea9ddb5264c4d792600a16b9a96ad0e9 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Mon, 23 Nov 2026 03:33:31 +0200 Subject: [PATCH 1/4] Release `v1.1.4`. --- CHANGELOG.md | 4 ++++ README.md | 4 ++-- pom.xml | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11a1a74e..60c8ffda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## Release Notes +`1.1.4` + +--- + `1.1.3` - Added `ExtendedField.valueNotNull()` to check whether the field value is not `null`, usable as a predicate for `ExtendedFields.findAllNonStatic`. diff --git a/README.md b/README.md index 3de9bb15..9e76dc69 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ A library that exposes general Java utility and reflection methods and a package ### Releases -Current release `1.1.3` +Current release `1.1.4` ### Documentation @@ -88,6 +88,6 @@ Maven: add this dependency to your `pom.xml` io.github.raduking morphix-all - 1.1.3 + 1.1.4 ``` diff --git a/pom.xml b/pom.xml index 4c2cdaff..a1534c10 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ io.github.raduking morphix-all - 1.1.3 + 1.1.4 jar ${project.groupId}:${project.artifactId} From bdc42f91d3b5f98268244b5a3c4d2bc917783f84 Mon Sep 17 00:00:00 2001 From: raduking Date: Mon, 23 Nov 2026 03:53:38 +0200 Subject: [PATCH 2/4] More test coverage. --- .../reflection/FieldsSafeGetByPathsTest.java | 14 ++++++++++++++ .../org/morphix/reflection/FieldsSafeGetTest.java | 7 +++++++ 2 files changed, 21 insertions(+) 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; From 460d8d1bc0348986e7a90f737b2baa62b3979036 Mon Sep 17 00:00:00 2001 From: raduking Date: Wed, 25 Nov 2026 02:55:00 +0200 Subject: [PATCH 3/4] Added `Threads.safeJoin`. --- CHANGELOG.md | 2 + .../java/org/morphix/lang/thread/Threads.java | 23 +++++++++ .../org/morphix/lang/thread/ThreadsTest.java | 49 +++++++++++++++++++ 3 files changed, 74 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 60c8ffda..12b9ec93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ `1.1.4` +- Added `Threads.safeJoin(Thread, Duration)` to join a thread with a timeout, with `InterruptedException` handling. + --- `1.1.3` 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/ThreadsTest.java b/src/test/java/org/morphix/lang/thread/ThreadsTest.java index 3330d8c2..059d83b1 100644 --- a/src/test/java/org/morphix/lang/thread/ThreadsTest.java +++ b/src/test/java/org/morphix/lang/thread/ThreadsTest.java @@ -405,6 +405,55 @@ void shouldSafelyWaitForCountdownLatchWithDurationAndHandleInterruptedExceptionO assertFalse(countReached.get()); assertFalse(result); } + + @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 From 96faa144616886c83af31a36ec3900744c1adf54 Mon Sep 17 00:00:00 2001 From: raduking Date: Wed, 25 Nov 2026 03:19:29 +0200 Subject: [PATCH 4/4] More mutation coverage. --- .../lang/thread/ReschedulingTaskTest.java | 273 ++++++++++++++++++ .../lang/thread/StackedContextHolderTest.java | 47 +++ .../morphix/lang/thread/SynchronizedTest.java | 53 ++++ .../org/morphix/lang/thread/ThreadsTest.java | 216 ++++++++++++++ 4 files changed, 589 insertions(+) diff --git a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java index 1049a724..e00585a4 100644 --- a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java +++ b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java @@ -47,6 +47,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; @@ -1334,5 +1335,277 @@ 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("[{}] 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 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); + } + + @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); + + 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 059d83b1..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 @@ -406,6 +453,68 @@ void shouldSafelyWaitForCountdownLatchWithDurationAndHandleInterruptedExceptionO 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); @@ -621,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 @@ -707,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