Class CleanableThread

java.lang.Object
java.lang.Thread
org.daiitech.naftah.builtin.utils.concurrent.CleanableThread
All Implemented Interfaces:
Runnable

public class CleanableThread extends Thread
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
  • Field Details

    • cleaner

      private final Runnable cleaner
  • Constructor Details

    • CleanableThread

      public CleanableThread(Runnable target)
      Constructs a CleanableThread with no cleaner.
      Parameters:
      target - the main task to run in this thread
    • CleanableThread

      public CleanableThread(Runnable target, Runnable cleaner)
      Constructs a CleanableThread with a cleaner.
      Parameters:
      target - the main task to run in this thread
      cleaner - a cleanup task to run after target completes; may be null
  • Method Details

    • run

      public void run()
      Runs the thread's task and ensures the cleaner is executed afterward.
      Specified by:
      run in interface Runnable
      Overrides:
      run in class Thread