2. Code Example

Below is the code for the ThreadScopeRunnable class. It can be used to wrap another Runnable so when it's finished running it clears the current thread scoped variables in order for destruction callbacks to run. If you have your own custom Thread implementations, they can call ThreadScopeContextHolder.currentThreadScopeAttributes().clear() directly.

                
public class ThreadScopeRunnable implements Runnable {
    
    protected Runnable target = null;

    /**
     * Constructor
     */
    public ThreadScopeRunnable(Runnable target) {
        this.target = target;
    }

    /**
     * Runs <code>Runnable</code> target and 
     * then afterword processes thread scope 
     * destruction callbacks.
     */
    public final void run() {
        try {
            target.run();
        } finally {
            ThreadScopeContextHolder.currentThreadScopeAttributes().clear();
        }
    }

}