1/*
2 * Copyright 2014 Google Inc.  All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/**
25 * @test
26 * @bug 8062771 8016236
27 * @summary Test publication of Class objects via a data race
28 * @run testng ThreadSafety
29 */
30
31import java.io.File;
32import java.net.URL;
33import java.net.URLClassLoader;
34import java.nio.file.Path;
35import java.nio.file.Paths;
36import java.util.Collections;
37import java.util.concurrent.BrokenBarrierException;
38import java.util.concurrent.Callable;
39import java.util.concurrent.CyclicBarrier;
40import java.util.concurrent.ExecutionException;
41import java.util.concurrent.ExecutorService;
42import java.util.concurrent.Executors;
43import java.util.concurrent.Future;
44import java.util.concurrent.TimeoutException;
45import static java.util.concurrent.TimeUnit.SECONDS;
46import static org.testng.Assert.*;
47import org.testng.annotations.Test;
48
49/**
50 * A test resulting from an attempt to repro this failure (in guice):
51 *
52 * java.lang.NullPointerException
53 *   at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
54 *   at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
55 *   at sun.reflect.generics.repository.ClassRepository.getSuperclass(ClassRepository.java:84)
56 *   at java.lang.Class.getGenericSuperclass(Class.java:692)
57 *   at com.google.inject.TypeLiteral.getSuperclassTypeParameter(TypeLiteral.java:99)
58 *   at com.google.inject.TypeLiteral.<init>(TypeLiteral.java:79)
59 *
60 * However, as one would expect with thread safety problems in reflection, these
61 * are very hard to reproduce.  This very test has never been observed to fail,
62 * but a similar test has been observed to fail about once in 2000 executions
63 * (about once every 6 CPU-hours), in jdk7 only.  It appears to be fixed in jdk8+ by:
64 *
65 * 8016236: Class.getGenericInterfaces performance improvement.
66 * (by making Class.genericInfo volatile)
67 */
68public class ThreadSafety {
69    public static class EmptyClass {
70        public static class EmptyGenericSuperclass<T> {}
71        public static class EmptyGenericSubclass<T> extends EmptyGenericSuperclass<T> {}
72    }
73
74    /** published via data race */
75    private Class<?> racyClass = Object.class;
76
77    private Class<?> createNewEmptyGenericSubclassClass() throws Exception {
78        String[] cpaths = System.getProperty("test.classes", ".")
79                                .split(File.pathSeparator);
80        URL[] urls = new URL[cpaths.length];
81        for (int i=0; i < cpaths.length; i++) {
82            urls[i] = Paths.get(cpaths[i]).toUri().toURL();
83        }
84        URLClassLoader ucl = new URLClassLoader(urls, null);
85        return Class.forName("ThreadSafety$EmptyClass$EmptyGenericSubclass", true, ucl);
86    }
87
88    @Test
89    public void testRacy_getGenericSuperclass() throws Exception {
90        final int nThreads = 10;
91        final int iterations = 30;
92        final int timeout = 10;
93        final CyclicBarrier newCycle = new CyclicBarrier(nThreads);
94        final Callable<Void> task = new Callable<Void>() {
95            public Void call() throws Exception {
96                for (int i = 0; i < iterations; i++) {
97                    final int threadId;
98                    try {
99                        threadId = newCycle.await(timeout, SECONDS);
100                    } catch (BrokenBarrierException e) {
101                        return null;
102                    }
103                    for (int j = 0; j < iterations; j++) {
104                        // one thread publishes the class object via a data
105                        // race, for the other threads to consume.
106                        if (threadId == 0) {
107                            racyClass = createNewEmptyGenericSubclassClass();
108                        } else {
109                            racyClass.getGenericSuperclass();
110                        }
111                    }
112                }
113                return null;
114            }};
115
116        final ExecutorService pool = Executors.newFixedThreadPool(nThreads);
117        try {
118            for (Future<Void> future :
119                     pool.invokeAll(Collections.nCopies(nThreads, task))) {
120                try {
121                    future.get(iterations * timeout, SECONDS);
122                } catch (ExecutionException e) {
123                    // ignore "collateral damage"
124                    if (!(e.getCause() instanceof BrokenBarrierException)
125                        &&
126                        !(e.getCause() instanceof TimeoutException)) {
127                        throw e;
128                    }
129                }
130            }
131        } finally {
132            pool.shutdownNow();
133            assertTrue(pool.awaitTermination(2 * timeout, SECONDS));
134        }
135    }
136}
137