1 import jdk.incubator.code.CodeReflection;
 2 import jdk.incubator.code.Op;
 3 import jdk.incubator.code.interpreter.Interpreter;
 4 import org.testng.Assert;
 5 import org.testng.annotations.Test;
 6 
 7 import jdk.incubator.code.Quotable;
 8 
 9 import java.lang.invoke.MethodHandles;
10 import java.util.function.IntSupplier;
11 import java.util.function.IntUnaryOperator;
12 import java.util.stream.IntStream;
13 
14 /*
15  * @test
16  * @summary test that invoking Op#ofQuotable returns the same instance
17  * @modules jdk.incubator.code
18  * @run testng QuotedSameInstanceTest
19  */
20 
21 public class QuotedSameInstanceTest {
22 
23     private static final Quotable q1 = (Quotable & Runnable) () -> {
24     };
25 
26     @Test
27     void testWithOneThread() {
28         Assert.assertSame(Op.ofQuotable(q1).get(), Op.ofQuotable(q1).get());
29     }
30 
31     interface QuotableIntUnaryOperator extends IntUnaryOperator, Quotable { }
32     private static final QuotableIntUnaryOperator q2 = x -> x;
33 
34     @Test
35     void testWithMultiThreads() {
36         Object[] quotedObjects = IntStream.range(0, 1024).parallel().mapToObj(__ -> Op.ofQuotable(q2).get()).toArray();
37         for (int i = 1; i < quotedObjects.length; i++) {
38             Assert.assertSame(quotedObjects[i], quotedObjects[i - 1]);
39         }
40     }
41 
42     public interface QuotableIntSupplier extends IntSupplier, Quotable {}
43     @CodeReflection
44     static Quotable q() {
45         QuotableIntSupplier r = () -> 8;
46         return r;
47     }
48 
49     @Test
50     void testMultiThreadsViaInterpreter() throws NoSuchMethodException {
51         var qm = this.getClass().getDeclaredMethod("q");
52         var q = Op.ofMethod(qm).get();
53         Quotable quotable = (Quotable) Interpreter.invoke(MethodHandles.lookup(), q);
54         Object[] quotedObjects = IntStream.range(0, 1024).parallel().mapToObj(__ -> Op.ofQuotable(quotable).get()).toArray();
55         for (int i = 1; i < quotedObjects.length; i++) {
56             Assert.assertSame(quotedObjects[i], quotedObjects[i - 1]);
57         }
58     }
59 }