Skip to content
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
## Release Notes

`1.1.4`

- Added `Threads.safeJoin(Thread, Duration)` to join a thread with a timeout, with `InterruptedException` handling.
- Fixed `ReschedulingTask.enable()` to throw `IllegalStateException` after the task has been closed.
- Changed `ReschedulingTask.close()` to mark the task permanently closed before cleaning up resources.
- Fixed `ReschedulingTask.disable()` to preserve a concurrent enable while cancellation finishes.
- Added `ReschedulingTask.isNotScheduled()` to report whether there is no pending scheduled execution.

---

`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
71 changes: 57 additions & 14 deletions src/main/java/org/morphix/lang/thread/ReschedulingTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

Expand All @@ -46,15 +45,37 @@
* any future executions and cancel any currently scheduled task. The task also provides a close method to clean up
* resources when it is no longer needed.
* <p>
* Useful for token refreshers, cache refreshers, heartbeat mechanisms, etc.
* <ul>
* <li>TODO: add tests for the exact logging messages</li>
* </ul>
* Whether the task is enabled and whether a scheduler future is still pending are separate concerns. The task may be
* enabled with no pending future while the initial refresh runs on the thread that called {@link #enable()}, or after a
* scheduled run has finished and the tracked future reference has been cleared.
* <p>
* Useful for token refreshers, cache refreshers, heart-beat mechanisms, etc.
*
* @author Radu Sebastian LAZIN
*/
public class ReschedulingTask implements AutoCloseable {

/**
* Lifecycle states. A closed task cannot be enabled again.
*/
private enum State {

/**
* The task is inactive and can be enabled.
*/
DISABLED,

/**
* The task is active and can execute and reschedule itself. Does not imply a pending scheduled future.
*/
ENABLED,

/**
* The task is permanently inactive and cannot be enabled again.
*/
CLOSED
}

/**
* Name space class for default values. Other defaults which are not constants:
* <ul>
Expand Down Expand Up @@ -168,10 +189,9 @@ private Default() {
private final Duration terminationTimeout;

/**
* Atomic flag to indicate whether the task is enabled or disabled. When disabled, the task will not execute or
* reschedule itself.
* Atomic lifecycle state. Only enabled tasks execute or reschedule themselves, and closing is permanent.
*/
private final AtomicBoolean enabled = new AtomicBoolean(false);
private final AtomicReference<State> state = new AtomicReference<>(State.DISABLED);

/**
* Atomic reference to the currently scheduled task. This allows for safe cancellation and rescheduling across threads.
Expand Down Expand Up @@ -224,15 +244,15 @@ 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.
* <p>
* Note: the scheduled task (future) and the scheduler will only be closed if the scheduler is managed by this instance.
*
* @throws Exception if an error occurs during closing
*/
@Override
public void close() throws Exception {
enabled.set(false);
state.set(State.CLOSED);
boolean cancelled = cancelScheduledTask();
scheduler.closeIfManaged(() -> closeRefreshScheduler(cancelled));
}
Expand Down Expand Up @@ -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();
}
}
Expand All @@ -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)) {
Expand All @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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();
}

/**
Expand All @@ -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.
*
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
Loading