private boolean invokeExistingSagas( EventProxy<?> event, Class<? extends Saga> sagaType, Collection<AssociationValue> associationValues) { Set<String> sagas = new TreeSet<>(); for (AssociationValue associationValue : associationValues) { sagas.addAll(sagaRepository.find(sagaType, associationValue)); } for (Saga sagaInCreation : sagasInCreation.values()) { if (sagaType.isInstance(sagaInCreation) && containsAny(sagaInCreation.getAssociationValues(), associationValues)) { sagas.add(sagaInCreation.getSagaIdentifier()); } } boolean sagaOfTypeInvoked = false; for (final String sagaId : sagas) { if (synchronizeSagaAccess) { lock.obtainLock(sagaId); Saga invokedSaga = null; try { invokedSaga = loadAndInvoke(event, sagaId, associationValues); if (invokedSaga != null) { sagaOfTypeInvoked = true; } } finally { doReleaseLock(sagaId, invokedSaga); } } else { loadAndInvoke(event, sagaId, associationValues); } } return sagaOfTypeInvoked; }
private void startNewSaga( EventProxy<?> event, Class<? extends Saga> sagaType, AssociationValue associationValue) { Saga newSaga = sagaFactory.createSaga(sagaType); newSaga.getAssociationValues().add(associationValue); preProcessSaga(newSaga); sagasInCreation.put(newSaga.getSagaIdentifier(), newSaga); try { if (synchronizeSagaAccess) { lock.obtainLock(newSaga.getSagaIdentifier()); try { doInvokeSaga(event, newSaga); } finally { try { sagaRepository.add(newSaga); } finally { doReleaseLock(newSaga.getSagaIdentifier(), newSaga); } } } else { try { doInvokeSaga(event, newSaga); } finally { sagaRepository.add(newSaga); } } } finally { removeEntry(newSaga.getSagaIdentifier(), sagasInCreation); } }
private void doReleaseLock(final String sagaId, final Saga sagaInstance) { if (sagaInstance == null || !CurrentUnitOfWork.isStarted()) { lock.releaseLock(sagaId); } else if (CurrentUnitOfWork.isStarted()) { CurrentUnitOfWork.get() .registerListener( new UnitOfWorkListenerAdapter() { @Override public void onCleanup(UnitOfWork unitOfWork) { // a reference to the saga is maintained to prevent it from GC until after the UoW // commit lock.releaseLock(sagaInstance.getSagaIdentifier()); } }); } }