AnsweredAssumed Answered

Synchronization issue in parallel multi-instance call activity

Question asked by alexander.tsvetkov.93 on Nov 23, 2016
Latest reply on Jan 4, 2017 by alexander.tsvetkov.93
Hi guys,

I am working on a task, where I need to have a multi-instance callActivity, which iterates over a collection and is executed in parallel. However, I may have found an issue in the synchronization of the threads that execute the started sub-processes, because in most of my tests, two threads try to update the values of nrOfCompletedInstances and nrOfActiveInstances at the same time. When this happens, these two variables are left with wrong values.

For example, I found the following lines in Activiti's debug logs (they are also attached):

11:17:53,623 [pool-1-thread-2] Multi-instance 'Activity(callactivity1)' instance completed. Details: loopCounter=1, nrOrCompletedInstances=1,nrOfActiveInstances=7,nrOfInstances=8
11:17:53,626 [pool-1-thread-1] Multi-instance 'Activity(callactivity1)' instance completed. Details: loopCounter=0, nrOrCompletedInstances=1,nrOfActiveInstances=7,nrOfInstances=8

As you can see, these two threads try to update the variables at nearly the same time and the second one sets wrong values for them. Instead of setting 2 for nrOfCompletedInstances and 6 for nrOfActiveInstances, it sets 1 and 7, respectively.

I looked around the Activiti engine's source code and the issue seems to be in the org.activiti.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior's leave() method. There, the values of nrOfCompletedInstances and nrOfActiveInstances are retrieved from the execution, incremented (or decremented) and then set back into the execution. These two operations are not in a synchronized block, however, nor are they in a separate DB transaction. This probably leads to the following situation:

1) Thread 1 retrieves the variables and they have values: nrOfCompletedInstances = 0, nrOfActiveInstances = 8.
2) Thread 2 retrieves the variables, before Thread 1 updates them and they have the same values: nrOfCompletedInstances = 0, nrOfActiveInstances = 8.
3) Both of them modify the variables independently, resulting in the values: nrOfCompletedInstances = 1, nrOfActiveInstances = 7.
4) Both of them attempt to set them back into the execution with these wrong values.

Is this a known issue and if so, have you made any plans for fixing it soon (I can try to submit a pull request)? Should I create an issue in Activiti's JIRA?

Note: The attached maven project contains my BPMN diagrams (I attached it as a .txt file, since the forum does not allow ZIP files *pardon*).

Thanks and best regards,