AnsweredAssumed Answered

Synchronization puzzle

Question asked by fritz128 on Oct 3, 2013
Latest reply on Oct 4, 2013 by fritz128
To understand why I decide to use a semaphore for async process launching You should use the whole post In other case you can read only question section.
Question:
Can I synchronously launch asynchronous subprocess? I mean (see code below), if I release semaphore inside a asynchronous subprocess, can I stop for-loop till the async subprocess will be started?

for (int i = 0; i < 10; i++) {
  semaphore.acquire();
  runtimeService.signalEventReceived(…); //Launch async subprocess, inside which I release the semaphore
}


My worflow diagram:
http://s1023.photobucket.com/user/bahmatjuk/media/processdiagram_zps180927cd.png.html?sort=3&o=0

What I have
Multiple asynchronous subprocesses that are started by signal.
I launch my subprocesses in for loop from 'B' user task. But each subprocess should contain variables with the same name.. It's very importand, because when I start subprocesses in for-loop with signalEventReceived method I can write only to global context, and then rewrite them to local context. It means that I should use some synchronization to ensure that the next subprocess won't rewrite global context before the previous copy variables to it own local context

Synchronization:
I achieve synchronization with help of semaphore:
handler bean (outside of activiti process)

for (int intVar: intVarList) {
  semaphore.acquire(); //ACQUIRE SEMAPHORE
  Map<String, Object> globalVars = new HashMap<String, Object>();
  globalVars.put("var", intVar);
  runtimeService.signalEventReceived("launchCandidateSubprocess", mainProcessExecution.getId(), globalVars);
}

And then in each subprocess:

public class FirstSubprocessService implements JavaDelegate [
  @Override
  public void execute(delegateExecution execution) {
     //……
     Integer localVar = (Integer) execution.get("var");
     execution.setVariableLocal("var", localVar);
     semaphore.release(); // RELEASE THE SAME SEMAPHORE
  }
}


What a problem:
I acquire semaphore in the main thread, but I have to release semaphore in async subprocess! Activiti doesn't run new async subprocess directly from runtimeService.signalEventReceived method. It means that 'ACQUIRE SEMAPHORE' line reaches before async subprocess is launched, as a result before it can release a semaphore

FAQ:
Q1: Why not multiinstance?
A1: Because I don't know how many subprocesses should I start. I may want to start additional subprocesses in any moment.
Q2: Are semaphores in handler and FirstSubprocessService the same?
A2: Yes. I manage this with help of SingletonSemaphorefactoryBean.

Outcomes