-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
JIOFeature.java
325 lines (278 loc) · 11.3 KB
/
JIOFeature.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package effects;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.StructuredTaskScope;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import static java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor;
public class JIOFeature {
public static class JIO<T> {
private Optional<T> value = Optional.empty();
private Optional<CompletableFuture<T>> futureValue = Optional.empty();
private Optional<Throwable> error = Optional.empty();
private JIO(T value) {
this.value = Optional.of(value);
}
private JIO(Throwable error) {
this.error = Optional.of(error);
}
private JIO() {
this.value = Optional.empty();
}
public JIO(CompletableFuture<T> futureValue) {
this.futureValue = Optional.of(futureValue);
}
public static <T> JIO<T> from(T value) {
return new JIO<>(value);
}
public static <T> JIO<T> fromEffect(Supplier<T> action) {
try {
return new JIO<>(action.get());
} catch (Exception e) {
return new JIO<>(e);
}
}
public static <T> JIO<T> fromOptional(Optional<T> value) {
return value.map(JIO::new)
.orElseGet(JIO::new);
}
public static <T> JIO<T> fromFuture(Supplier<T> action) {
CompletableFuture<T> future = CompletableFuture.supplyAsync(action, newVirtualThreadPerTaskExecutor());
return new JIO<>(future);
}
public JIO<T> map(Function<T, T> func) {
if (value.isPresent() && error.isEmpty()) {
try {
return new JIO<>(func.apply(value.get()));
} catch (Exception e) {
this.value = Optional.empty();
this.error = Optional.of(e);
return this;
}
}
return this;
}
public JIO<T> flatMap(Function<T, JIO<T>> func) {
if (value.isPresent() && error.isEmpty()) {
try {
return func.apply(value.get());
} catch (Exception e) {
this.value = Optional.empty();
this.error = Optional.of(e);
return this;
}
}
return this;
}
public JIO<T> mapAsync(Function<T, T> func) {
if (value.isPresent() && error.isEmpty()) {
CompletableFuture<T> future = CompletableFuture.supplyAsync(() -> func.apply(value.get()), newVirtualThreadPerTaskExecutor());
return new JIO<>(future);
}
if (futureValue.isPresent() && error.isEmpty()) {
return new JIO<>(futureValue.get().thenApply(func));
}
try {
final T value = this.get();
return new JIO<>(CompletableFuture.supplyAsync(() -> value, newVirtualThreadPerTaskExecutor()));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
public JIO<T> parallelAsync(Function<T, T> func1, Function<T, T> func2, BiFunction<T, T, T> mergeFunc) throws InterruptedException {
if (value.isPresent() && error.isEmpty()) {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
StructuredTaskScope.Subtask<T> task1 = scope.fork(() -> func1.apply(value.get()));
StructuredTaskScope.Subtask<T> task2 = scope.fork(() -> func2.apply(value.get()));
var maybeSideEffect = scope.join().exception();
if (maybeSideEffect.isPresent()) {
error = maybeSideEffect;
} else {
this.value = Optional.of(mergeFunc.apply(task1.get(), task2.get()));
}
return this;
}
} else {
return this;
}
}
public JIO<T> race(Function<T, T> func1, Function<T, T> func2) throws ExecutionException, InterruptedException {
if (value.isPresent() && error.isEmpty()) {
CompletableFuture<T> asyncTask1 = CompletableFuture.supplyAsync(() -> func1.apply(value.get()), newVirtualThreadPerTaskExecutor());
CompletableFuture<T> asyncTask2 = CompletableFuture.supplyAsync(() -> func2.apply(value.get()), newVirtualThreadPerTaskExecutor());
T result = (T) CompletableFuture.anyOf(asyncTask1, asyncTask2).get();
asyncTask1.cancel(true);
asyncTask2.cancel(true);
value = Optional.of(result);
}
return this;
}
public JIO<T> filter(Function<T, Boolean> func) {
if (value.isPresent() && error.isEmpty()) {
try {
if (!func.apply(value.get())) {
this.value = Optional.empty();
}
} catch (Exception e) {
this.value = Optional.empty();
this.error = Optional.of(e);
return this;
}
}
return this;
}
public JIO<T> onSuccess(Consumer<T> func) {
if (value.isPresent() && error.isEmpty()) {
try {
func.accept(value.get());
} catch (Exception e) {
this.value = Optional.empty();
this.error = Optional.of(e);
return this;
}
}
return this;
}
public <T> JIO<T> onFailure(Consumer<Throwable> func) {
if (error.isPresent()) {
try {
func.accept(error.get());
} catch (Exception e) {
this.error = Optional.of(e);
return (JIO<T>) this;
}
}
return (JIO<T>) this;
}
public boolean isPresent() {
return value.isPresent();
}
public boolean isEmpty() {
return value.isEmpty();
}
public boolean isSucceed() {
return error.isEmpty();
}
public boolean isFailure() {
return error.isPresent();
}
public T get() throws Throwable {
if (value.isEmpty()) {
throw new IllegalStateException("No value present");
} else if (error.isPresent()) {
throw error.get();
}
return value.get();
}
public T getAsync() throws Throwable {
if (futureValue.isEmpty()) {
throw new IllegalStateException("No value present");
} else if (error.isPresent()) {
throw error.get();
}
return futureValue.get().get();
}
public T getOrElse(T defaultValue) {
if (value.isEmpty() || error.isPresent()) {
return defaultValue;
}
return value.get();
}
@Override
public String toString() {
if (isEmpty()) {
return "Empty";
} else if (isFailure()) {
return STR."Side-effect detected:\{error.toString()}";
} else {
return STR."Value(\{value})";
}
}
}
@Test
public void effectSystem() throws Throwable {
Optional<String> optionalWithValue = Optional.of("Hello");
JIO<String> optionalEffect = JIO.fromOptional(optionalWithValue)
.map(effect -> STR."\{effect} world")
.onSuccess(v -> System.out.println(STR."We found a value \{v}"));
System.out.println(optionalEffect);
JIO<String> errorEffect = JIO.fromEffect(() -> "Hello world without side-effects")
.map(effect -> STR."\{effect}!");
System.out.println(errorEffect);
JIO<String> nullEffect = JIO.fromOptional(Optional.empty());
System.out.println(nullEffect.getOrElse("Let's use a backup"));
}
@Test
public void sideEffects() {
Optional<String> optionalWithoutValue = Optional.empty();
JIO<String> optionalEffect = JIO.fromOptional(optionalWithoutValue);
System.out.println(optionalEffect);
System.out.println(optionalEffect.isEmpty());
System.out.println(optionalEffect.isPresent());
JIO<String> errorEffect = JIO.fromEffect(() -> {
throw new NullPointerException();
})
.onFailure(t -> System.out.println(STR."We found a side effect. Caused by \{t.getMessage()}"));
System.out.println(errorEffect);
System.out.println(errorEffect.isSucceed());
System.out.println(errorEffect.isFailure());
}
@Test
public void transform() throws Throwable {
JIO<String> map = JIO.fromOptional(Optional.of("Let's transform this value"))
.map(String::toUpperCase)
.map(value -> STR."[\{value}]");
System.out.println(map);
}
@Test
public void composition() {
JIO<String> composition = JIO.fromEffect(() -> "Hello JIO")
.map(value -> STR."\{value}!")
.flatMap(value -> JIO.fromOptional(Optional.of(STR."\{value} together is better")));
System.out.println(composition);
}
@Test
public void async() throws Throwable {
JIO<String> futureProgram = JIO.fromFuture(() -> "Hello from")
.mapAsync(d -> STR."\{d} the future");
System.out.println(futureProgram.getAsync());
JIO<String> asyncProgram = JIO.fromEffect(() -> "Hello JIO")
.mapAsync(value -> STR."\{value}!")
.mapAsync(value -> STR."\{value}!!");
System.out.println(asyncProgram.getAsync());
}
@Test
public void parallel() throws Throwable {
JIO<String> parallelProgram = JIO.from("")
.parallelAsync(_ -> "Hello", _ -> "world", (hello, world) -> STR."\{hello} \{world}")
.map(String::toUpperCase);
System.out.println(parallelProgram.get());
}
@Test
public void race() throws Throwable {
JIO<String> raceProgram = JIO.from("Race start.")
.race(v -> {
try {
Thread.sleep(new Random().nextInt(1000));
return STR."\{v} Renault win";
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, v -> {
try {
Thread.sleep(new Random().nextInt(1000));
return STR."\{v} Fiat win";
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
})
.map(String::toUpperCase);
System.out.println(raceProgram.get());
}
}