1 import jdk.incubator.code.Reflect;
 2 import jdk.incubator.code.Op;
 3 import jdk.incubator.code.Quoted;
 4 import org.junit.jupiter.api.Assertions;
 5 import org.junit.jupiter.api.Test;
 6 
 7 import java.util.List;
 8 import java.util.function.IntUnaryOperator;
 9 import java.util.stream.IntStream;
10 import java.util.stream.Stream;
11 
12 /*
13  * @test
14  * @modules jdk.incubator.code
15  * @run junit TestOpOfQuotable
16  */
17 public class TestOpOfQuotable {
18 
19     Runnable f() {
20         return (@Reflect Runnable) () -> {
21             System.out.println("Running...");
22         };
23     }
24 
25     @Test
26     public void testWithLambdaThatDoNotCaptureInSequence() {
27         Runnable q1 = f();
28         Runnable q2 = f();
29         Quoted quoted1 = Op.ofQuotable(q1).orElseThrow();
30         Quoted quoted2 = Op.ofQuotable(q2).orElseThrow();
31         Assertions.assertSame(quoted1.op(), quoted2.op());
32     }
33 
34     @Test
35     public void testWithLambdaThatDoNotCaptureInParallel() { // parallel
36         Runnable q1 = f();
37         Runnable q2 = f();
38         List<Op> ops = Stream.of(q1, q2).parallel().map(q -> Op.ofQuotable(q).orElseThrow().op()).toList();
39         Assertions.assertSame(ops.getFirst(), ops.getLast());
40     }
41 
42     static IntUnaryOperator g(int i) {
43         return (@Reflect IntUnaryOperator) j -> j + i;
44     }
45 
46     @Test
47     public void testWithLambdaThatCaptureInSequence() {
48         IntUnaryOperator q1 = g(1);
49         IntUnaryOperator q2 = g(2);
50         Quoted quoted1 = Op.ofQuotable(q1).orElseThrow();
51         Quoted quoted2 = Op.ofQuotable(q2).orElseThrow();
52         Assertions.assertSame(quoted1.op(), quoted2.op());
53     }
54 
55     @Test
56     public void testWithLambdaThatCaptureInParallel() {
57         IntUnaryOperator q1 = g(1);
58         IntUnaryOperator q2 = g(2);
59         List<Op> ops = Stream.of(q1, q2).parallel().map(q -> Op.ofQuotable(q).orElseThrow().op()).toList();
60         Assertions.assertSame(ops.getFirst(), ops.getLast());
61     }
62 
63     @Test
64     public void testQuotedIsSameInSequence() {
65         int j = 8;
66         IntUnaryOperator q = (@Reflect IntUnaryOperator) i -> i * 2 + j;
67         Quoted q1 = Op.ofQuotable(q).get();
68         Quoted q2 = Op.ofQuotable(q).get();
69         Assertions.assertSame(q1, q2);
70     }
71 
72     @Test
73     public void testQuotedIsSameInParallel() {
74         int j = 8;
75         IntUnaryOperator q = (@Reflect IntUnaryOperator) i -> i * 2 + j;
76         List<Quoted> quotedObjects = IntStream.range(1, 3).parallel().mapToObj(_ -> Op.ofQuotable(q).get()).toList();
77         Assertions.assertSame(quotedObjects.getFirst(), quotedObjects.getLast());
78     }
79 }