AnsweredAssumed Answered

Multi-threading and transactions

Question asked by herve.quiroz on Sep 23, 2008
Latest reply on Sep 23, 2008 by herve.quiroz
Within a repository action, we need to run some CPU-eating code that would benefit well from multi-threading. The main problem is that this code is accessing content from Alfresco (read and write), which means it needs authentication and an active transaction.

I tried several approaches already with no success so far. I think we get two options here:
  • Start threads within the current transaction and ensure that they are able to re-use the current transaction. I would assume that transaction information is stored in some ThreadLocal facility, which means that using a common ThreadGroup could be a way to let the child threads re-use the transaction.

  • Pass a current transaction reference to the child threads and then start a new nested transaction in each thread.
In each case, the main objective is to let all work from all threads be commited or rolled back at once.

To illustrate my point, here is small piece of code:

final NodeRef nodeRef = …

newTransaction();

final Thread thread = new Thread(new Runnable()
{
   public void run()
   {
      nodeService.addAspect(nodeRef, ContentModel.ASPECT_CLASSIFIABLE, null);
   });

thread.start();
thread.join();

commit();

newTransaction();
assert nodeService.hasAspect(nodeRef, ContentModel.ASPECT_CLASSIFIABLE);
commit();
As you may have guessed already, newTransaction() and commit() are fictional methods.
The assertion fails. There is also some error in the console (uncaught exception obviously) regarding the missing active transaction that occurs during the run() method invocation from the child thread.

So, is there a way to run multiple threads within a transaction so that I can have the 3 other lazy CPU cores compute something for a change? ;)

Outcomes