cancel
Showing results for 
Search instead for 
Did you mean: 

Multi-threading and transactions

herve_quiroz
Champ in-the-making
Champ in-the-making
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? Smiley Wink
2 REPLIES 2

pmonks
Star Contributor
Star Contributor
I don't believe a single Alfresco transaction can be used in more than a single thread, in large part because Hibernate (the ORM tool Alfresco uses internally) doesn't support this mode of operation (Hibernate sessions do not support multi-threading - each thread must have its own Hibernate session).

Cheers,
Peter

herve_quiroz
Champ in-the-making
Champ in-the-making
I was more or less expecting such bad news… Since my post, I have read even more pages on the subject (hibernate vs threads).
Thanks for your help.