Skip to content
Open
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
## Release Notes

`1.1.4`

- Added `Threads.safeJoin(Thread, Duration)` to join a thread with a timeout, with `InterruptedException` handling.

---

`1.1.3`

- Added `ExtendedField.valueNotNull()` to check whether the field value is not `null`, usable as a predicate for `ExtendedFields.findAllNonStatic`.
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -88,6 +88,6 @@ Maven: add this dependency to your `pom.xml`
<dependency>
<groupId>io.github.raduking</groupId>
<artifactId>morphix-all</artifactId>
<version>1.1.3</version>
<version>1.1.4</version>
</dependency>
```
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

<groupId>io.github.raduking</groupId>
<artifactId>morphix-all</artifactId>
<version>1.1.3</version>
<version>1.1.4</version>
<packaging>jar</packaging>

<name>${project.groupId}:${project.artifactId}</name>
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/org/morphix/lang/thread/Threads.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
* <p>
* 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.<br/>
* By default, when using: {@code Threads.execute(runnables, ExecutionType.EXECUTOR)} the single thread executor will be
Expand Down
273 changes: 273 additions & 0 deletions src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<ReschedulingTask> 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<ScheduledExecutorService> 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]"));
}
}
}
Loading