1/*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation.
7 *
8 * This code is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11 * version 2 for more details (a copy is included in the LICENSE file that
12 * accompanied this code).
13 *
14 * You should have received a copy of the GNU General Public License version
15 * 2 along with this work; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
17 *
18 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
19 * or visit www.oracle.com if you need additional information or have any
20 * questions.
21 */
22
23/*
24 * This file is available under and governed by the GNU General Public
25 * License version 2 only, as published by the Free Software Foundation.
26 * However, the following notice accompanied the original version of this
27 * file:
28 *
29 * Written by Doug Lea and Martin Buchholz with assistance from
30 * members of JCP JSR-166 Expert Group and released to the public
31 * domain, as explained at
32 * http://creativecommons.org/publicdomain/zero/1.0/
33 */
34
35/*
36 * @test
37 * @bug 8004138
38 * @modules java.base/java.util.concurrent:open
39 * @summary Checks that ForkJoinTask thrown exceptions are not leaked.
40 * This whitebox test is sensitive to forkjoin implementation details.
41 */
42
43import static java.util.concurrent.TimeUnit.SECONDS;
44
45import java.lang.ref.WeakReference;
46import java.lang.reflect.Field;
47import java.util.ArrayList;
48import java.util.concurrent.CountDownLatch;
49import java.util.concurrent.ForkJoinPool;
50import java.util.concurrent.ForkJoinTask;
51import java.util.concurrent.RecursiveAction;
52import java.util.function.BooleanSupplier;
53
54public class FJExceptionTableLeak {
55    static class FailingTaskException extends RuntimeException {}
56    static class FailingTask extends RecursiveAction {
57        public void compute() { throw new FailingTaskException(); }
58    }
59
60    static int bucketsInuse(Object[] exceptionTable) {
61        int count = 0;
62        for (Object x : exceptionTable)
63            if (x != null) count++;
64        return count;
65    }
66
67    public static void main(String[] args) throws Exception {
68        final ForkJoinPool pool = new ForkJoinPool(4);
69        final Field exceptionTableField =
70            ForkJoinTask.class.getDeclaredField("exceptionTable");
71        exceptionTableField.setAccessible(true);
72        final Object[] exceptionTable = (Object[]) exceptionTableField.get(null);
73
74        if (bucketsInuse(exceptionTable) != 0) throw new AssertionError();
75
76        final ArrayList<FailingTask> tasks = new ArrayList<>();
77
78        // Keep submitting failing tasks until most of the exception
79        // table buckets are in use
80        do {
81            for (int i = 0; i < exceptionTable.length; i++) {
82                FailingTask task = new FailingTask();
83                pool.execute(task);
84                tasks.add(task); // retain strong refs to all tasks, for now
85            }
86            for (FailingTask task : tasks) {
87                try {
88                    task.join();
89                    throw new AssertionError("should throw");
90                } catch (FailingTaskException success) {}
91            }
92        } while (bucketsInuse(exceptionTable) < exceptionTable.length * 3 / 4);
93
94        // Retain a strong ref to one last failing task;
95        // task.join() will trigger exception table expunging.
96        FailingTask lastTask = tasks.get(0);
97
98        // Clear all other strong refs, making exception table cleanable
99        tasks.clear();
100
101        BooleanSupplier exceptionTableIsClean = () -> {
102            try {
103                lastTask.join();
104                throw new AssertionError("should throw");
105            } catch (FailingTaskException expected) {}
106            int count = bucketsInuse(exceptionTable);
107            if (count == 0)
108                throw new AssertionError("expected to find last task");
109            return count == 1;
110        };
111        gcAwait(exceptionTableIsClean);
112    }
113
114    // --------------- GC finalization infrastructure ---------------
115
116    /** No guarantees, but effective in practice. */
117    static void forceFullGc() {
118        CountDownLatch finalizeDone = new CountDownLatch(1);
119        WeakReference<?> ref = new WeakReference<Object>(new Object() {
120            protected void finalize() { finalizeDone.countDown(); }});
121        try {
122            for (int i = 0; i < 10; i++) {
123                System.gc();
124                if (finalizeDone.await(1L, SECONDS) && ref.get() == null) {
125                    System.runFinalization(); // try to pick up stragglers
126                    return;
127                }
128            }
129        } catch (InterruptedException unexpected) {
130            throw new AssertionError("unexpected InterruptedException");
131        }
132        throw new AssertionError("failed to do a \"full\" gc");
133    }
134
135    static void gcAwait(BooleanSupplier s) {
136        for (int i = 0; i < 10; i++) {
137            if (s.getAsBoolean())
138                return;
139            forceFullGc();
140        }
141        throw new AssertionError("failed to satisfy condition");
142    }
143}
144