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. There is also a ThreadScopeCallable class for wrapping a Callable. 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();
        }
    }

}