File tree Expand file tree Collapse file tree 4 files changed +72
-0
lines changed Expand file tree Collapse file tree 4 files changed +72
-0
lines changed Original file line number Diff line number Diff line change
1
+ package app .work ;
2
+
3
+ import java .util .ArrayDeque ;
4
+ import java .util .ArrayList ;
5
+ import java .util .Deque ;
6
+ import java .util .List ;
7
+
8
+ public class CommandExecutor {
9
+ List <ICommand > commands = new ArrayList <>();
10
+ Deque <Runnable > undos = new ArrayDeque <>();
11
+
12
+ public void add (ICommand cmd ) {
13
+ this .commands .add (cmd );
14
+ }
15
+
16
+ public boolean execute () {
17
+ for (var cmd : commands ) {
18
+ try {
19
+ var undo = cmd .execute ();
20
+ undos .push (undo );
21
+ } catch (Exception e ) {
22
+ for (var undo : undos ) {
23
+ undo .run ();
24
+ }
25
+ }
26
+ }
27
+ return true ;
28
+ }
29
+
30
+ interface ICommand {
31
+ Runnable execute () throws Exception ;
32
+ }
33
+ }
Original file line number Diff line number Diff line change
1
+ package app .work ;
2
+
3
+ // public interface ICommand {
4
+ // void execute();
5
+ // }
Original file line number Diff line number Diff line change
1
+ package app .work ;
2
+
3
+ import java .util .Optional ;
4
+
5
+ import com .fasterxml .jackson .annotation .JsonInclude ;
6
+
7
+ @ JsonInclude (JsonInclude .Include .NON_EMPTY )
8
+ public record Person (String name , int age , Optional <String > job ) {
9
+ public Person (String name , int age ) {
10
+ this (name , age , Optional .empty ());
11
+ }
12
+ }
Original file line number Diff line number Diff line change @@ -81,6 +81,28 @@ public String hello() {
81
81
return "bar" ;
82
82
}
83
83
84
+ @ GetMapping ("zach" )
85
+ public Person zach () {
86
+ return new Person ("zach" , 31 );
87
+ }
88
+
89
+ @ PostMapping ("commands" )
90
+ public Person commands (@ RequestBody Person person ) {
91
+ var executor = new CommandExecutor ();
92
+ var n = new Object () { int value = person .age (); };
93
+ executor .add (() -> {
94
+ var rand = ThreadLocalRandom .current ().nextInt (5 );
95
+ if (rand < 3 ) {
96
+ throw new Exception ("Oops!" );
97
+ }
98
+ n .value += rand ;
99
+ return () -> {
100
+ };
101
+ });
102
+ executor .execute ();
103
+ return new Person (person .name (), n .value );
104
+ }
105
+
84
106
@ WithSpan
85
107
private void doSomeWork (int time ) throws InterruptedException {
86
108
log .info ("doing work for " + time + "ms" );
You can’t perform that action at this time.
0 commit comments