Class CleanableThread
java.lang.Object
java.lang.Thread
org.daiitech.naftah.builtin.utils.concurrent.CleanableThread
- All Implemented Interfaces:
Runnable
A thread wrapper that ensures a cleanup action is executed
after the thread finishes, regardless of whether it terminates normally
or due to an exception.
This class extends Thread and adds an optional cleaner
Runnable that will be executed in the finally block
after the main Runnable completes.
Usage example:
Runnable task = () -> System.out.println("Task running");
Runnable cleanup = () -> System.out.println("Cleanup after task");
Thread t = new CleanableThread(task, cleanup);
t.start();
This is useful for automatically cleaning thread-local variables, releasing resources, or performing other post-execution tasks.
- Author:
- Chakib Daii
-
Nested Class Summary
Nested classes/interfaces inherited from class java.lang.Thread
Thread.State, Thread.UncaughtExceptionHandler -
Field Summary
FieldsFields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY -
Constructor Summary
ConstructorsConstructorDescriptionCleanableThread(Runnable target) Constructs a CleanableThread with no cleaner.CleanableThread(Runnable target, Runnable cleaner) Constructs a CleanableThread with a cleaner. -
Method Summary
Modifier and TypeMethodDescriptionvoidrun()Runs the thread's task and ensures the cleaner is executed afterward.Methods inherited from class java.lang.Thread
activeCount, checkAccess, clone, countStackFrames, currentThread, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, onSpinWait, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, suspend, toString, yield
-
Field Details
-
cleaner
-
-
Constructor Details
-
CleanableThread
Constructs a CleanableThread with no cleaner.- Parameters:
target- the main task to run in this thread
-
CleanableThread
Constructs a CleanableThread with a cleaner.- Parameters:
target- the main task to run in this threadcleaner- a cleanup task to run aftertargetcompletes; may benull
-
-
Method Details