undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,184 @@
/*
* Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @summary Test ForkJoinPool.shutdownNow with threads blocked in invokeXXX and Future.get
* @run junit AsyncShutdownNow
*/
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static java.lang.Thread.State.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;
class AsyncShutdownNow {
// long running interruptible task
private static final Callable<Void> SLEEP_FOR_A_DAY = () -> {
Thread.sleep(Duration.ofDays(1));
return null;
};
static Stream<ForkJoinPool> pools() {
return Stream.of(
new ForkJoinPool(),
new ForkJoinPool(1)
);
}
/**
* Test shutdownNow with a running task and main thread blocked in Future::get.
*/
@ParameterizedTest
@MethodSource("pools")
void testFutureGet(ForkJoinPool pool) throws Exception {
try (pool) {
Future<?> future = pool.submit(SLEEP_FOR_A_DAY);
// shutdownNow when main thread waits in ForkJoinTask.awaitDone
onWait("java.util.concurrent.ForkJoinTask.awaitDone", pool::shutdownNow);
try {
future.get();
fail();
} catch (ExecutionException | CancellationException e) {
// expected
}
}
}
/**
* Test shutdownNow with a running task and main thread blocked in a timed Future::get.
*/
@ParameterizedTest
@MethodSource("pools")
void testTimedFutureGet(ForkJoinPool pool) throws Exception {
try (pool) {
Future<?> future = pool.submit(SLEEP_FOR_A_DAY);
// shutdownNow when main thread waits in ForkJoinTask.awaitDone
onWait("java.util.concurrent.ForkJoinTask.awaitDone", pool::shutdownNow);
try {
future.get(1, TimeUnit.HOURS);
fail();
} catch (ExecutionException | CancellationException e) {
// expected
}
}
}
/**
* Test shutdownNow with running tasks and main thread blocked in invokeAll.
*/
@ParameterizedTest
@MethodSource("pools")
void testInvokeAll(ForkJoinPool pool) throws Exception {
try (pool) {
// shutdownNow when main thread waits in ForkJoinTask.awaitDone
onWait("java.util.concurrent.ForkJoinTask.awaitDone", pool::shutdownNow);
List<Future<Void>> futures = pool.invokeAll(List.of(SLEEP_FOR_A_DAY, SLEEP_FOR_A_DAY));
for (Future<Void> f : futures) {
assertTrue(f.isDone());
try {
Object result = f.get();
fail();
} catch (ExecutionException | CancellationException e) {
// expected
}
}
}
}
/**
* Test shutdownNow with running tasks and main thread blocked in invokeAny.
*/
@ParameterizedTest
@MethodSource("pools")
void testInvokeAny(ForkJoinPool pool) throws Exception {
try (pool) {
// shutdownNow when main thread waits in ForkJoinTask.get
onWait("java.util.concurrent.ForkJoinTask.get", pool::shutdownNow);
try {
pool.invokeAny(List.of(SLEEP_FOR_A_DAY, SLEEP_FOR_A_DAY));
fail();
} catch (ExecutionException e) {
// expected
}
}
}
/**
* Runs the given action when the current thread is sampled as waiting (timed or
* untimed) at the given location. The location takes the form "{@code c.m}" where
* {@code c} is the fully qualified class name and {@code m} is the method name.
*/
private void onWait(String location, Runnable action) {
int index = location.lastIndexOf('.');
String className = location.substring(0, index);
String methodName = location.substring(index + 1);
Thread target = Thread.currentThread();
var thread = new Thread(() -> {
try {
boolean found = false;
while (!found) {
Thread.State state = target.getState();
assertTrue(state != TERMINATED);
if ((state == WAITING || state == TIMED_WAITING)
&& contains(target.getStackTrace(), className, methodName)) {
found = true;
} else {
Thread.sleep(20);
}
}
action.run();
} catch (Exception e) {
e.printStackTrace();
}
});
thread.setDaemon(true);
thread.start();
}
/**
* Returns true if the given stack trace contains an element for the given class
* and method name.
*/
private boolean contains(StackTraceElement[] stack, String className, String methodName) {
return Arrays.stream(stack)
.anyMatch(e -> className.equals(e.getClassName())
&& methodName.equals(e.getMethodName()));
}
}

View file

@ -0,0 +1,101 @@
/*
* Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @run testng AsyncShutdownNowInvokeAny
* @summary A variant of AsyncShutdownNow useful for race bug hunting
*/
// TODO: reorganize all of the AsyncShutdown tests
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class AsyncShutdownNowInvokeAny {
// long running interruptible task
private static final Callable<Void> SLEEP_FOR_A_DAY = () -> {
Thread.sleep(86400_000);
return null;
};
private ScheduledExecutorService scheduledExecutor;
@BeforeClass
public void setup() {
scheduledExecutor = Executors.newScheduledThreadPool(1);
}
@AfterClass
public void teardown() {
scheduledExecutor.shutdown();
}
/**
* Schedule the given executor service to be shutdown abruptly after the given
* delay, in seconds.
*/
private void scheduleShutdownNow(ExecutorService executor, int delayInSeconds) {
scheduledExecutor.schedule(() -> {
executor.shutdownNow();
return null;
}, delayInSeconds, TimeUnit.SECONDS);
}
/**
* Test shutdownNow with thread blocked in invokeAny.
*/
@Test
public void testInvokeAny() throws Exception {
final int reps = 4;
for (int rep = 1; rep < reps; rep++) {
ExecutorService pool = new ForkJoinPool(1);
scheduleShutdownNow(pool, 5);
try {
try {
// execute long running tasks
pool.invokeAny(List.of(SLEEP_FOR_A_DAY, SLEEP_FOR_A_DAY));
assertTrue(false);
} catch (ExecutionException | RejectedExecutionException e) {
// expected
}
} finally {
pool.shutdown();
}
}
}
}

View file

@ -0,0 +1,199 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @run testng AsyncShutdownNowInvokeAnyRace
* @summary A variant of AsyncShutdownNow useful for race bug hunting
*/
// TODO: reorganize all of the AsyncShutdown tests
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.lang.management.ManagementFactory;
import java.lang.management.LockInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class AsyncShutdownNowInvokeAnyRace {
// TODO: even more jitter-inducing parallelism?
// int nThreads = ThreadLocalRandom.current().nextInt(1, 50);
// ExecutorService pool = Executors.newCachedThreadPool();
// Callable<Void> task = () -> { testInvokeAny_1(); return null; };
// List<Callable<Void>> tasks = Collections.nCopies(nThreads, task);
// try {
// for (Future<Void> future : pool.invokeAll(tasks)) {
// future.get();
// }
// } finally {
// pool.shutdown();
// }
// }
// public void testInvokeAny_1() throws Exception {
/**
* Test shutdownNow with thread blocked in invokeAny.
*/
@Test
public void testInvokeAny() throws Exception {
final int reps = 30_000;
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int falseAlarms = 0;
for (int rep = 1; rep < reps; rep++) {
ForkJoinPool pool = new ForkJoinPool(1);
CountDownLatch pleaseShutdownNow = new CountDownLatch(1);
int nTasks = rnd.nextInt(2, 5);
AtomicInteger threadsStarted = new AtomicInteger(0);
AtomicReference<String> poolAtShutdownNow = new AtomicReference<>();
Callable<Void> blockPool = () -> {
threadsStarted.getAndIncrement();
// await submission quiescence; may false-alarm
// TODO: consider re-checking to reduce false alarms
while (threadsStarted.get() + pool.getQueuedSubmissionCount() < nTasks)
Thread.yield();
pleaseShutdownNow.countDown();
Thread.sleep(86400_000);
return null;
};
List<Callable<Void>> tasks = Collections.nCopies(nTasks, blockPool);
Runnable shutdown = () -> {
try {
pleaseShutdownNow.await();
poolAtShutdownNow.set(pool.toString());
pool.shutdownNow();
} catch (Throwable t) { throw new AssertionError(t); }
};
Future<Void> shutdownResult = CompletableFuture.runAsync(shutdown);
try {
try {
if (rnd.nextBoolean())
pool.invokeAny(tasks, 10L, SECONDS);
else
pool.invokeAny(tasks);
throw new AssertionError("should throw");
} catch (RejectedExecutionException re) {
falseAlarms++;
} catch (CancellationException re) {
} catch (ExecutionException ex) {
Throwable cause = ex.getCause();
if (!(cause instanceof InterruptedException) &&
!(cause instanceof CancellationException))
throw ex;
} catch (TimeoutException ex) {
dumpTestThreads();
int i = rep;
String detail = String.format(
"invokeAny timed out, "
+ "nTasks=%d rep=%d threadsStarted=%d%n"
+ "poolAtShutdownNow=%s%n"
+ "poolAtTimeout=%s%n"
+ "queuedTaskCount=%d queuedSubmissionCount=%d",
nTasks, i, threadsStarted.get(),
poolAtShutdownNow,
pool,
pool.getQueuedTaskCount(),
pool.getQueuedSubmissionCount());
throw new AssertionError(detail, ex);
}
} finally {
pool.shutdown();
}
if (falseAlarms != 0)
System.out.println("Premature shutdowns = " + falseAlarms);
shutdownResult.get();
}
}
//--- thread stack dumping (from JSR166TestCase.java) ---
private static final ThreadMXBean THREAD_MXBEAN
= ManagementFactory.getThreadMXBean();
/** Returns true if thread info might be useful in a thread dump. */
static boolean threadOfInterest(ThreadInfo info) {
final String name = info.getThreadName();
String lockName;
if (name == null)
return true;
if (name.equals("Signal Dispatcher")
|| name.equals("WedgedTestDetector"))
return false;
if (name.equals("Reference Handler")) {
// Reference Handler stacktrace changed in JDK-8156500
StackTraceElement[] stackTrace; String methodName;
if ((stackTrace = info.getStackTrace()) != null
&& stackTrace.length > 0
&& (methodName = stackTrace[0].getMethodName()) != null
&& methodName.equals("waitForReferencePendingList"))
return false;
// jdk8 Reference Handler stacktrace
if ((lockName = info.getLockName()) != null
&& lockName.startsWith("java.lang.ref"))
return false;
}
if ((name.equals("Finalizer") || name.equals("Common-Cleaner"))
&& (lockName = info.getLockName()) != null
&& lockName.startsWith("java.lang.ref"))
return false;
if (name.startsWith("ForkJoinPool.commonPool-worker")
&& (lockName = info.getLockName()) != null
&& lockName.startsWith("java.util.concurrent.ForkJoinPool"))
return false;
return true;
}
/**
* A debugging tool to print stack traces of most threads, as jstack does.
* Uninteresting threads are filtered out.
*/
static void dumpTestThreads() {
System.err.println("------ stacktrace dump start ------");
for (ThreadInfo info : THREAD_MXBEAN.dumpAllThreads(true, true))
if (threadOfInterest(info))
System.err.print(info);
System.err.println("------ stacktrace dump end ------");
}
}

View file

@ -0,0 +1,56 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8368500
* @run junit/othervm ContextClassLoaderTest
* @summary Check the context classloader is reset
*/
import java.net.URL;
import java.net.URLClassLoader;
import java.util.concurrent.Future;
import java.util.concurrent.ForkJoinPool;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ContextClassLoaderTest {
@Test
void testContextClassLoaderIsSetAndRestored() throws Exception {
Future<?> future = ForkJoinPool.commonPool().submit(() -> {
Thread thread = Thread.currentThread();
ClassLoader originalCCL = thread.getContextClassLoader();
ClassLoader customCCL = new URLClassLoader(new URL[0], originalCCL);
// Set custom context classloader and verify it
thread.setContextClassLoader(customCCL);
assertSame(customCCL, thread.getContextClassLoader(), "Custom context class loader not set");
// Reset to original and verify restoration
thread.setContextClassLoader(originalCCL);
assertSame(originalCCL, thread.getContextClassLoader(), "Original context class loader not restored");
});
future.get();
}
}

View file

@ -0,0 +1,265 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* @test
* @bug 6865571
* @summary Numerical Integration using fork/join
* @run main Integrate reps=1 forkPolicy=dynamic
* @run main Integrate reps=1 forkPolicy=serial
* @run main Integrate reps=1 forkPolicy=fork
*/
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
/**
* Sample program using Gaussian Quadrature for numerical integration.
* This version uses a simplified hardwired function. Inspired by a
* <A href="http://www.cs.uga.edu/~dkl/filaments/dist.html">
* Filaments</A> demo program.
*/
public final class Integrate {
static final double errorTolerance = 1.0e-11;
/** for time conversion */
static final long NPS = (1000L * 1000 * 1000);
static final int SERIAL = -1;
static final int DYNAMIC = 0;
static final int FORK = 1;
/** the function to integrate */
static double computeFunction(double x) {
return (x * x + 1.0) * x;
}
static final double start = 0.0;
static final double end = 1536.0;
/**
* The number of recursive calls for
* integrate from start to end.
* (Empirically determined)
*/
static final int calls = 263479047;
static String keywordValue(String[] args, String keyword) {
for (String arg : args)
if (arg.startsWith(keyword))
return arg.substring(keyword.length() + 1);
return null;
}
static int intArg(String[] args, String keyword, int defaultValue) {
String val = keywordValue(args, keyword);
return (val == null) ? defaultValue : Integer.parseInt(val);
}
static int policyArg(String[] args, String keyword, int defaultPolicy) {
String val = keywordValue(args, keyword);
if (val == null) return defaultPolicy;
if (val.equals("dynamic")) return DYNAMIC;
if (val.equals("serial")) return SERIAL;
if (val.equals("fork")) return FORK;
throw new Error();
}
/**
* Usage: Integrate [procs=N] [reps=N] forkPolicy=serial|dynamic|fork
*/
public static void main(String[] args) throws Exception {
final int procs = intArg(args, "procs",
Runtime.getRuntime().availableProcessors());
final int forkPolicy = policyArg(args, "forkPolicy", DYNAMIC);
ForkJoinPool g = new ForkJoinPool(procs);
System.out.println("Integrating from " + start + " to " + end +
" forkPolicy = " + forkPolicy);
long lastTime = System.nanoTime();
for (int reps = intArg(args, "reps", 10); reps > 0; reps--) {
double a;
if (forkPolicy == SERIAL)
a = SQuad.computeArea(g, start, end);
else if (forkPolicy == FORK)
a = FQuad.computeArea(g, start, end);
else
a = DQuad.computeArea(g, start, end);
long now = System.nanoTime();
double s = (double) (now - lastTime) / NPS;
lastTime = now;
System.out.printf("Calls/sec: %12d", (long) (calls / s));
System.out.printf(" Time: %7.3f", s);
System.out.printf(" Area: %12.1f", a);
System.out.println();
}
System.out.println(g);
g.shutdown();
}
// Sequential version
static final class SQuad extends RecursiveAction {
static double computeArea(ForkJoinPool pool, double l, double r) {
SQuad q = new SQuad(l, r, 0);
pool.invoke(q);
return q.area;
}
final double left; // lower bound
final double right; // upper bound
double area;
SQuad(double l, double r, double a) {
this.left = l; this.right = r; this.area = a;
}
public final void compute() {
double l = left;
double r = right;
area = recEval(l, r, (l * l + 1.0) * l, (r * r + 1.0) * r, area);
}
static final double recEval(double l, double r, double fl,
double fr, double a) {
double h = (r - l) * 0.5;
double c = l + h;
double fc = (c * c + 1.0) * c;
double hh = h * 0.5;
double al = (fl + fc) * hh;
double ar = (fr + fc) * hh;
double alr = al + ar;
if (Math.abs(alr - a) <= errorTolerance)
return alr;
else
return recEval(c, r, fc, fr, ar) + recEval(l, c, fl, fc, al);
}
}
//....................................
// ForkJoin version
static final class FQuad extends RecursiveAction {
static double computeArea(ForkJoinPool pool, double l, double r) {
FQuad q = new FQuad(l, r, 0);
pool.invoke(q);
return q.area;
}
final double left; // lower bound
final double right; // upper bound
double area;
FQuad(double l, double r, double a) {
this.left = l; this.right = r; this.area = a;
}
public final void compute() {
double l = left;
double r = right;
area = recEval(l, r, (l * l + 1.0) * l, (r * r + 1.0) * r, area);
}
static final double recEval(double l, double r, double fl,
double fr, double a) {
double h = (r - l) * 0.5;
double c = l + h;
double fc = (c * c + 1.0) * c;
double hh = h * 0.5;
double al = (fl + fc) * hh;
double ar = (fr + fc) * hh;
double alr = al + ar;
if (Math.abs(alr - a) <= errorTolerance)
return alr;
FQuad q = new FQuad(l, c, al);
q.fork();
ar = recEval(c, r, fc, fr, ar);
if (!q.tryUnfork()) {
q.quietlyJoin();
return ar + q.area;
}
return ar + recEval(l, c, fl, fc, al);
}
}
// ...........................
// Version using on-demand Fork
static final class DQuad extends RecursiveAction {
static double computeArea(ForkJoinPool pool, double l, double r) {
DQuad q = new DQuad(l, r, 0);
pool.invoke(q);
return q.area;
}
final double left; // lower bound
final double right; // upper bound
double area;
DQuad(double l, double r, double a) {
this.left = l; this.right = r; this.area = a;
}
public final void compute() {
double l = left;
double r = right;
area = recEval(l, r, (l * l + 1.0) * l, (r * r + 1.0) * r, area);
}
static final double recEval(double l, double r, double fl,
double fr, double a) {
double h = (r - l) * 0.5;
double c = l + h;
double fc = (c * c + 1.0) * c;
double hh = h * 0.5;
double al = (fl + fc) * hh;
double ar = (fr + fc) * hh;
double alr = al + ar;
if (Math.abs(alr - a) <= errorTolerance)
return alr;
DQuad q = null;
if (getSurplusQueuedTaskCount() <= 3)
(q = new DQuad(l, c, al)).fork();
ar = recEval(c, r, fc, fr, ar);
if (q != null && !q.tryUnfork()) {
q.quietlyJoin();
return ar + q.area;
}
return ar + recEval(l, c, fl, fc, al);
}
}
}

View file

@ -0,0 +1,174 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* @test
* @bug 6865571
* @summary Solve NQueens using fork/join
* @run main NQueensCS maxBoardSize=11 reps=1
* @run main NQueensCS maxBoardSize=11 reps=1 procs=8
*/
import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class NQueensCS extends RecursiveAction {
static long lastStealCount;
static int boardSize;
static final int[] expectedSolutions = new int[] {
0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200,
73712, 365596, 2279184, 14772512, 95815104, 666090624
}; // see http://www.durangobill.com/N_Queens.html
static String keywordValue(String[] args, String keyword) {
for (String arg : args)
if (arg.startsWith(keyword))
return arg.substring(keyword.length() + 1);
return null;
}
static int intArg(String[] args, String keyword, int defaultValue) {
String val = keywordValue(args, keyword);
return (val == null) ? defaultValue : Integer.parseInt(val);
}
/** for time conversion */
static final long NPS = (1000L * 1000L * 1000L);
/**
* Usage: NQueensCS [minBoardSize=N] [maxBoardSize=N] [procs=N] [reps=N]
*/
public static void main(String[] args) throws Exception {
// Board sizes too small: hard to measure well.
// Board sizes too large: take too long to run.
final int minBoardSize = intArg(args, "minBoardSize", 8);
final int maxBoardSize = intArg(args, "maxBoardSize", 15);
final int procs = intArg(args, "procs", 0);
for (int reps = intArg(args, "reps", 10); reps > 0; reps--) {
ForkJoinPool g = (procs == 0) ?
new ForkJoinPool() :
new ForkJoinPool(procs);
lastStealCount = g.getStealCount();
for (int i = minBoardSize; i <= maxBoardSize; i++)
test(g, i);
System.out.println(g);
g.shutdown();
}
}
static void test(ForkJoinPool g, int i) throws Exception {
boardSize = i;
int ps = g.getParallelism();
long start = System.nanoTime();
NQueensCS task = new NQueensCS(new int[0]);
g.invoke(task);
int solutions = task.solutions;
long time = System.nanoTime() - start;
double secs = (double) time / NPS;
if (solutions != expectedSolutions[i])
throw new Error();
System.out.printf("NQueensCS %3d", i);
System.out.printf(" Time: %7.3f", secs);
long sc = g.getStealCount();
long ns = sc - lastStealCount;
lastStealCount = sc;
System.out.printf(" Steals/t: %5d", ns/ps);
System.out.println();
}
// Boards are represented as arrays where each cell
// holds the column number of the queen in that row
final int[] sofar;
NQueensCS nextSubtask; // to link subtasks
int solutions;
NQueensCS(int[] a) {
this.sofar = a;
}
public final void compute() {
NQueensCS subtasks;
int bs = boardSize;
if (sofar.length >= bs)
solutions = 1;
else if ((subtasks = explore(sofar, bs)) != null)
solutions = processSubtasks(subtasks);
}
private static NQueensCS explore(int[] array, int bs) {
int row = array.length;
NQueensCS s = null; // subtask list
outer:
for (int q = 0; q < bs; ++q) {
for (int i = 0; i < row; i++) {
int p = array[i];
if (q == p || q == p - (row - i) || q == p + (row - i))
continue outer; // attacked
}
NQueensCS first = s; // lag forks to ensure 1 kept
if (first != null)
first.fork();
int[] next = Arrays.copyOf(array, row+1);
next[row] = q;
NQueensCS subtask = new NQueensCS(next);
subtask.nextSubtask = first;
s = subtask;
}
return s;
}
private static int processSubtasks(NQueensCS s) {
// Always run first the task held instead of forked
s.compute();
int ns = s.solutions;
s = s.nextSubtask;
// Then the unstolen ones
while (s != null && s.tryUnfork()) {
s.compute();
ns += s.solutions;
s = s.nextSubtask;
}
// Then wait for the stolen ones
while (s != null) {
s.join();
ns += s.solutions;
s = s.nextSubtask;
}
return ns;
}
}

View file

@ -0,0 +1,56 @@
/*
* Copyright (c) 2004, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8322732
* @summary ForkJoinPool utilizes available workers even with arbitrary task dependencies
*/
import java.util.concurrent.Callable;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicInteger;
public class Starvation {
static final AtomicInteger count = new AtomicInteger();
static final Callable<Void> noop = new Callable<Void>() {
public Void call() {
return null; }};
static final class AwaitCount implements Callable<Void> {
private int c;
AwaitCount(int c) { this.c = c; }
public Void call() {
while (count.get() == c) Thread.onSpinWait();
return null; }};
public static void main(String[] args) throws Exception {
try (var pool = new ForkJoinPool(2)) {
for (int i = 0; i < 100_000; i++) {
var future1 = pool.submit(new AwaitCount(i));
var future2 = pool.submit(noop);
future2.get();
count.set(i + 1);
future1.get();
}
}
}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicBoolean;
import jdk.test.lib.Utils;
/*
* @test
* @bug 8078490
* @summary Test submission and execution of task without joining
* @library /test/lib
*/
public class SubmissionTest {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
static long millisElapsedSince(long startTime) {
return (System.nanoTime() - startTime) / (1000L * 1000L);
}
public static void main(String[] args) throws Throwable {
final ForkJoinPool e = new ForkJoinPool(1);
final AtomicBoolean b = new AtomicBoolean();
final Runnable setFalse = () -> b.set(false);
for (int i = 0; i < 30_000; i++) {
b.set(true);
e.execute(setFalse);
long startTime = System.nanoTime();
while (b.get()) {
if (millisElapsedSince(startTime) >= LONG_DELAY_MS) {
throw new RuntimeException("Submitted task failed to execute");
}
Thread.yield();
}
}
}
}

View file

@ -0,0 +1,135 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* @test
* @bug 8008378
* @summary Basic checks for parallelism 0, and null returning factory
* @run main/othervm -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 ThreadLessCommon
* @run main/othervm -Djava.util.concurrent.ForkJoinPool.common.threadFactory=ThreadLessCommon$NullForkJoinWorkerThreadFactory ThreadLessCommon
* @author Chris Hegarty
*/
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.RecursiveTask;
public class ThreadLessCommon {
static final int THRESHOLD = 1000;
static final boolean debug = true;
private static void realMain(String[] args) throws Throwable {
if (debug) {
String pp = System.getProperty(
"java.util.concurrent.ForkJoinPool.common.parallelism");
System.out.println(
"java.util.concurrent.ForkJoinPool.common.parallelism:" + pp);
String tf = System.getProperty(
"java.util.concurrent.ForkJoinPool.common.threadFactory");
System.out.println(
"java.util.concurrent.ForkJoinPool.common.threadFactory:" + tf);
}
long from = 0, to = 50000;
RecursiveTask<Long> task = new SumTask(from, to, Thread.currentThread());
long sum = task.invoke();
System.out.printf("%nSum: from [%d] to [%d] = [%d]%n", from, to, sum);
task.fork();
sum = task.join();
System.out.printf("%nSum: from [%d] to [%d] = [%d]%n", from, to, sum);
sum = ForkJoinPool.commonPool().invoke(task.fork());
System.out.printf("%nSum: from [%d] to [%d] = [%d]%n", from, to, sum);
}
static class SumTask extends RecursiveTask<Long> {
final Thread expectedThread;
final long from;
final long to;
SumTask(long from, long to, Thread thread) {
this.from = from; this.to = to; expectedThread = thread;
}
@Override
public Long compute() {
check(Thread.currentThread() == expectedThread,
"Expected " + expectedThread + ", got " + Thread.currentThread());
long range = to - from;
if (range < THRESHOLD) {
long acc = 0;
for (long i = from; i <= to; i++)
acc = acc + i;
return acc;
} else {
long half = from + range / 2;
SumTask t1 = new SumTask(from, half ,expectedThread);
SumTask t2 = new SumTask(half+1, to ,expectedThread);
if (half % 2 == 0) {
t1.fork();
return t2.compute() + t1.join();
} else {
invokeAll(t1, t2);
try { return t1.get() + t2.get(); }
catch (Exception x) { unexpected(x); return 0L;}
}
}
}
}
public static class NullForkJoinWorkerThreadFactory
implements ForkJoinWorkerThreadFactory
{
@Override
public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
return null;
}
}
//--------------------- Infrastructure ---------------------------
static volatile int passed = 0, failed = 0;
static void pass() {passed++;}
static void fail() {failed++; /*Thread.dumpStack();*/}
static void fail(String msg) {System.out.println(msg); fail();}
static void unexpected(Throwable t) {failed++; t.printStackTrace();}
static void check(boolean cond, String msg) {if (cond) pass(); else fail(msg);}
static void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
}

View file

@ -0,0 +1,85 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* @test
* @bug 8008378
* @run main/othervm -Djava.util.concurrent.ForkJoinPool.common.exceptionHandler=ThrowingRunnable
* ThrowingRunnable
* @summary FJP.execute(Runnable), uncaught exception should cause worker thread
* to die.
* @author Chris Hegarty
*/
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
public class ThrowingRunnable implements Runnable, UncaughtExceptionHandler {
static final Phaser phaser = new Phaser(2);
private static void realMain(String[] args) throws Throwable {
ThrowingRunnable r = new ThrowingRunnable();
ForkJoinPool.commonPool().execute(r);
phaser.awaitAdvanceInterruptibly(phaser.arrive(), 10, TimeUnit.SECONDS);
pass();
}
@Override
public void run() {
throw new RuntimeException("This is an exception.");
}
@Override
public void uncaughtException(Thread t, Throwable e) {
pass();
phaser.arrive();
}
//--------------------- Infrastructure ---------------------------
static volatile int passed = 0, failed = 0;
static void pass() {passed++;}
static void fail() {failed++; /*Thread.dumpStack();*/}
static void fail(String msg) {System.out.println(msg); fail();}
static void unexpected(Throwable t) {failed++; t.printStackTrace();}
static void check(boolean cond, String msg) {if (cond) pass(); else fail(msg);}
static void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
}

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8274349
* @run main/othervm -XX:ActiveProcessorCount=1 Uniprocessor
* @summary Check the default FJ pool has a reasonable default parallelism
* level in a uniprocessor environment.
*/
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ForkJoinPool;
public class Uniprocessor {
static volatile boolean done = false;
public static void main(String[] args) throws InterruptedException {
// If the default parallelism were zero then this task would not
// complete and the test will timeout.
CountDownLatch ran = new CountDownLatch(1);
ForkJoinPool.commonPool().submit(() -> ran.countDown());
ran.await();
}
}