!IMPORTANT because TAPESTRY-2141 is resolved in T5.0.11 there are two versions of the code

see also Tapestry5HowToWorkQueue

Questions about running tasks in separate thread were asked more than few times on the mailing list. The code is simple but some important things must be considered.

Most important thing is to call PerthreadManager.cleanup() after the thread is finished.

Other thing is that the separate thread will have different instances of any threaded services and will not have any user specific data. For example if you load an Hibernate entity inside the request thread and pass it to the task, the task will get a different Hibernate Session instance and will fail if you try to save the instance while the task is running (in a separate thread that is)

To save you some trouble I've created a simple service that runs tasks in a separate thread and makes sure PerthreadManager.cleanup()is called. You can inject it anywhere and call:

   1 _threadSource.runInThread(new Runnable(){
   2     public void run(){
   3         //do something
   4     }
   5 });

interface ThreadSource

   1 public interface ThreadSource {
   2 
   3     /** runs the task using default exception handler, which writes exception to the log */
   4     public abstract void runInThread(Runnable task);
   5 
   6     /** runs a task in a separate thread and makes sure that tapestry ioc resources are freed after
   7      * thread finishes.*/
   8     public abstract void runInThread(final Runnable task, final TaskExceptionHandler taskExceptionHandler);
   9 
  10 }

interface TaskExceptionHandler

   1 public interface TaskExceptionHandler {
   2     public void exceptionThrown(Object task, Throwable exception);
   3 }

T5.0.11

implementation for T5.0.11 and above (T5.0.11-SNASPSHOT included).You can modify it any way you like it, and even add a thread pool.

   1 import org.apache.tapestry.ioc.services.PerthreadManager;
   2 import org.slf4j.Logger;
   3 
   4 public class ThreadSourceImpl implements ThreadSource {
   5 
   6     private final PerthreadManager _perthreadManager;
   7     private final Logger _logger;
   8 
   9     public ThreadSourceImpl(PerthreadManager perthreadManager, Logger logger){
  10         _perthreadManager = perthreadManager;
  11         _logger = logger;
  12     }
  13     
  14     /* (non-Javadoc)
  15      * @see tapestryutil.services.ThreadSource#runInThread(java.lang.Runnable)
  16      */
  17     public void runInThread(Runnable task){
  18         runInThread(task,defaultTaskExceptionHandler);
  19     }
  20 
  21     /* (non-Javadoc)
  22      * @see tapestryutil.services.ThreadSource#runInThread(java.lang.Runnable, tapestryutil.services.TaskExceptionHandler)
  23      */
  24     public void runInThread(final Runnable task, final TaskExceptionHandler taskExceptionHandler){
  25         new Thread(new Runnable(){
  26 
  27             public void run() {
  28                 try {
  29                    task.run();
  30                 } catch (Throwable e) {
  31                     taskExceptionHandler.exceptionThrown(task, e);
  32                 } finally {
  33                     _perthreadManager.cleanup();
  34                 }
  35             }
  36             
  37         }).start();
  38     }
  39 
  40     /** default exception handler that writes exception to the log */
  41     private final TaskExceptionHandler defaultTaskExceptionHandler = new TaskExceptionHandler(){
  42         public void exceptionThrown(Object task, Throwable exception) {
  43             _logger.error("Task failed :"+task, exception);
  44         }
  45     };
  46     
  47 }

before T5.0.11

NOTICE: before T5.0.11 ThreadCleanupHub is used, and for T5.0.11 and later PerthreadManager replaces it.

Please notice that this workarround fixes only the issue with ThreadCleanupHub, but other ThreadLocal dependant code might fail. The workarround is also not needed for Java 6.

The bug mentioned for java 5 happens if ThreadLocal.initialValue() happens inside another ThreadLocal.initialValue(), this is exactly the case when any other threaded service is initialized. It is because PerThreadServiceCreator uses ThreadLocal and inside initValue() generates a new instance of a service by calling a build method, and build method for HibernateSesionManager adds a listener to ThreadCleanupHub (which gets initialized and calls initialValue()) and things get messed up... I'm probably not makin much sense ... so here's the workarround

declare a dummy listener inside ThreadSourceImpl:

   1     /** dummy listener to force initializing the ThreadLocal and avoid http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5025230*/
   2     private static final ThreadCleanupListener dummyListener = new ThreadCleanupListener(){public void threadDidCleanup() {}};

then add this as first line in the run method of the new created thread (before task.run()) adding the dummy listener is just to force creation of ThreadCleanupHub instance

_cleanupHub.addThreadCleanupListener(dummyListener);

for unpatient, here's the full code with workarround

   1 import org.apache.tapestry.ioc.services.ThreadCleanupHub;
   2 import org.apache.tapestry.ioc.services.ThreadCleanupListener;
   3 import org.slf4j.Logger;
   4 
   5 public class ThreadSourceImpl implements ThreadSource {
   6 
   7     private final ThreadCleanupHub _cleanupHub;
   8     private final Logger _logger;
   9 
  10     public ThreadSourceImpl(ThreadCleanupHub cleanupHub, Logger logger){
  11         _cleanupHub = cleanupHub;
  12         _logger = logger;
  13     }
  14     
  15     /* (non-Javadoc)
  16      * @see tapestryutil.services.ThreadSource#runInThread(java.lang.Runnable)
  17      */
  18     public void runInThread(Runnable task){
  19         runInThread(task,defaultTaskExceptionHandler);
  20     }
  21 
  22     /* (non-Javadoc)
  23      * @see tapestryutil.services.ThreadSource#runInThread(java.lang.Runnable, tapestryutil.services.TaskExceptionHandler)
  24      */
  25     public void runInThread(final Runnable task, final TaskExceptionHandler taskExceptionHandler){
  26         new Thread(new Runnable(){
  27 
  28             public void run() {
  29                 _cleanupHub.addThreadCleanupListener(dummyListener);
  30                 try {
  31                    task.run();
  32                 } catch (Throwable e) {
  33                     taskExceptionHandler.exceptionThrown(task, e);
  34                 } finally {
  35                     _cleanupHub.cleanup();
  36                 }
  37             }
  38             
  39         }).start();
  40     }
  41     
  42     /** dummy listener to force initializing the ThreadLocal and avoid http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5025230*/
  43     private static final ThreadCleanupListener dummyListener = new ThreadCleanupListener(){public void threadDidCleanup() {}};
  44 
  45     /** default exception handler that writes exception to the log */
  46     private final TaskExceptionHandler defaultTaskExceptionHandler = new TaskExceptionHandler(){
  47         public void exceptionThrown(Object task, Throwable exception) {
  48             _logger.error("Task failed :"+task, exception);
  49         }
  50     };
  51     
  52 }

Tapestry5HowToRunTaskInThread (last edited 2009-09-20 23:20:53 by localhost)