-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSagaExecutor.java
44 lines (38 loc) · 1.3 KB
/
SagaExecutor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package microservices.saga;
import java.util.ArrayList;
import java.util.List;
public class SagaExecutor {
private final List<SagaAction> actions;
public SagaExecutor() {
actions = new ArrayList<>();
}
public void addAction(SagaAction action) {
actions.add(action);
}
public void execute() {
List<SagaAction> completedActions = new ArrayList<>();
try {
for (SagaAction action : actions) {
action.execute();
completedActions.add(action);
Thread.sleep(500);
}
} catch (RuntimeException e) {
Main.errPrintln("Error occurred: '" + e.getMessage() + "', performing compensations.");
undo(completedActions);
} catch (InterruptedException e) {
}
}
private void undo(List<SagaAction> completedActions) {
// Undo all actions that have been completed so far
for (int i = completedActions.size() - 1; i >= 0; i--) {
try {
completedActions.get(i).compensate();
Thread.sleep(500);
} catch (RuntimeException e) {
Main.errPrintln("Error during compensation: '" + e.getMessage() + "'");
} catch (InterruptedException e) {
}
}
}
}