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