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,117 @@
/*
* Copyright (c) 2008, 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 6602600
* @run main/othervm/timeout=480 -Xmx64m BasicCancelTest
* @summary Check effectiveness of RemoveOnCancelPolicy
*/
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Simple timer cancellation test. Submits tasks to a scheduled executor
* service and immediately cancels them.
*/
public class BasicCancelTest {
void checkShutdown(final ExecutorService es) {
final Runnable nop = new Runnable() {public void run() {}};
try {
if (new Random().nextBoolean()) {
check(es.isShutdown());
if (es instanceof ThreadPoolExecutor)
check(((ThreadPoolExecutor) es).isTerminating()
|| es.isTerminated());
THROWS(RejectedExecutionException.class,
new F(){void f(){es.execute(nop);}});
}
} catch (Throwable t) { unexpected(t); }
}
void checkTerminated(final ThreadPoolExecutor tpe) {
try {
checkShutdown(tpe);
check(tpe.getQueue().isEmpty());
check(tpe.isTerminated());
check(! tpe.isTerminating());
equal(tpe.getActiveCount(), 0);
equal(tpe.getPoolSize(), 0);
equal(tpe.getTaskCount(), tpe.getCompletedTaskCount());
check(tpe.awaitTermination(0L, TimeUnit.SECONDS));
} catch (Throwable t) { unexpected(t); }
}
void test(String[] args) throws Throwable {
final ScheduledThreadPoolExecutor pool =
new ScheduledThreadPoolExecutor(1);
// Needed to avoid OOME
pool.setRemoveOnCancelPolicy(true);
final long moreThanYouCanChew = Runtime.getRuntime().maxMemory() / 32;
System.out.printf("moreThanYouCanChew=%d%n", moreThanYouCanChew);
Runnable noopTask = new Runnable() { public void run() {}};
for (long i = 0; i < moreThanYouCanChew; i++)
pool.schedule(noopTask, 10, TimeUnit.MINUTES).cancel(true);
pool.shutdown();
check(pool.awaitTermination(1L, TimeUnit.DAYS));
checkTerminated(pool);
equal(pool.getTaskCount(), 0L);
equal(pool.getCompletedTaskCount(), 0L);
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
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 {
new BasicCancelTest().instanceMain(args);}
void instanceMain(String[] args) throws Throwable {
try {test(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");}
abstract class F {abstract void f() throws Throwable;}
void THROWS(Class<? extends Throwable> k, F... fs) {
for (F f : fs)
try {f.f(); fail("Expected " + k.getName() + " not thrown");}
catch (Throwable t) {
if (k.isAssignableFrom(t.getClass())) pass();
else unexpected(t);}}
}

View file

@ -0,0 +1,113 @@
/*
* Copyright (c) 2007, 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 6560953
* @summary Test ScheduledThreadPoolExecutor.decorateTask
*/
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
public class DecorateTask {
Runnable countDownTask(final CountDownLatch latch) {
return new Runnable() { public void run() {
latch.countDown();
if (latch.getCount() <= 0)
throw new RuntimeException("done");
}};}
void test(String[] args) throws Throwable {
final int jobs = 100;
final AtomicInteger decoratorCount = new AtomicInteger(0);
final ScheduledThreadPoolExecutor pool =
new ScheduledThreadPoolExecutor(10) {
protected <V> RunnableScheduledFuture<V> decorateTask(
final Runnable runnable,
final RunnableScheduledFuture<V> task) {
return new RunnableScheduledFuture<V>() {
public void run() {
decoratorCount.incrementAndGet();
task.run();
}
public boolean isPeriodic() {
return task.isPeriodic();
}
public boolean cancel(boolean mayInterruptIfRunning) {
return task.cancel(mayInterruptIfRunning);
}
public boolean isCancelled() {
return task.isCancelled();
}
public boolean isDone() {
return task.isDone();
}
public V get()
throws InterruptedException, ExecutionException {
return task.get();
}
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return task.get(timeout, unit);
}
public long getDelay(TimeUnit unit) {
return task.getDelay(unit);
}
public int compareTo(Delayed o) {
return task.compareTo(o);
}};}};
final CountDownLatch latch1 = new CountDownLatch(jobs);
final CountDownLatch latch2 = new CountDownLatch(jobs);
pool.scheduleAtFixedRate(countDownTask(latch1), 0L, 1L, TimeUnit.NANOSECONDS);
pool.scheduleWithFixedDelay(countDownTask(latch2), 0L, 1L, TimeUnit.NANOSECONDS);
latch1.await();
latch2.await();
pool.shutdown();
pool.awaitTermination(1L, TimeUnit.MINUTES);
equal(decoratorCount.get(), 2 * jobs);
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
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 {
new DecorateTask().instanceMain(args);}
void instanceMain(String[] args) throws Throwable {
try {test(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,178 @@
/*
* 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 6725789
* @summary Check for long overflow in task time comparison.
* @library /test/lib
*/
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import jdk.test.lib.Utils;
public class DelayOverflow {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
static void waitForNanoTimeTick() {
for (long t0 = System.nanoTime(); t0 == System.nanoTime(); )
;
}
void scheduleNow(ScheduledThreadPoolExecutor pool,
Runnable r, int how) {
switch (how) {
case 0:
pool.schedule(r, 0, MILLISECONDS);
break;
case 1:
pool.schedule(Executors.callable(r), 0, DAYS);
break;
case 2:
pool.scheduleWithFixedDelay(r, 0, 1000, NANOSECONDS);
break;
case 3:
pool.scheduleAtFixedRate(r, 0, 1000, MILLISECONDS);
break;
default:
fail(String.valueOf(how));
}
}
void scheduleAtTheEndOfTime(ScheduledThreadPoolExecutor pool,
Runnable r, int how) {
switch (how) {
case 0:
pool.schedule(r, Long.MAX_VALUE, MILLISECONDS);
break;
case 1:
pool.schedule(Executors.callable(r), Long.MAX_VALUE, DAYS);
break;
case 2:
pool.scheduleWithFixedDelay(r, Long.MAX_VALUE, 1000, NANOSECONDS);
break;
case 3:
pool.scheduleAtFixedRate(r, Long.MAX_VALUE, 1000, MILLISECONDS);
break;
default:
fail(String.valueOf(how));
}
}
/**
* Attempts to test exhaustively and deterministically, all 20
* possible ways that one task can be scheduled in the maximal
* distant future, while at the same time an existing task's time
* has already expired.
*/
void test(String[] args) throws Throwable {
for (int nowHow = 0; nowHow < 4; nowHow++) {
for (int thenHow = 0; thenHow < 4; thenHow++) {
final ScheduledThreadPoolExecutor pool
= new ScheduledThreadPoolExecutor(1);
final CountDownLatch runLatch = new CountDownLatch(1);
final CountDownLatch busyLatch = new CountDownLatch(1);
final CountDownLatch proceedLatch = new CountDownLatch(1);
final Runnable notifier = new Runnable() {
public void run() { runLatch.countDown(); }};
final Runnable neverRuns = new Runnable() {
public void run() { fail(); }};
final Runnable keepPoolBusy = new Runnable() {
public void run() {
try {
busyLatch.countDown();
proceedLatch.await();
} catch (Throwable t) { unexpected(t); }
}};
pool.schedule(keepPoolBusy, 0, DAYS);
busyLatch.await();
scheduleNow(pool, notifier, nowHow);
waitForNanoTimeTick();
scheduleAtTheEndOfTime(pool, neverRuns, thenHow);
proceedLatch.countDown();
check(runLatch.await(LONG_DELAY_MS, MILLISECONDS));
equal(runLatch.getCount(), 0L);
pool.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
pool.shutdown();
}
final int nowHowCopy = nowHow;
final ScheduledThreadPoolExecutor pool
= new ScheduledThreadPoolExecutor(1);
final CountDownLatch runLatch = new CountDownLatch(1);
final Runnable notifier = new Runnable() {
public void run() { runLatch.countDown(); }};
final Runnable scheduleNowScheduler = new Runnable() {
public void run() {
try {
scheduleNow(pool, notifier, nowHowCopy);
waitForNanoTimeTick();
} catch (Throwable t) { unexpected(t); }
}};
pool.scheduleWithFixedDelay(scheduleNowScheduler,
0, Long.MAX_VALUE, NANOSECONDS);
check(runLatch.await(LONG_DELAY_MS, MILLISECONDS));
equal(runLatch.getCount(), 0L);
pool.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
pool.shutdown();
}
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
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 {
new DelayOverflow().instanceMain(args);}
void instanceMain(String[] args) throws Throwable {
try {test(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,141 @@
/*
* 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 and Martin Buchholz 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
* @summary Ensure that waiting pool threads don't retain refs to tasks.
*/
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class GCRetention {
/**
* A custom thread pool with a custom RunnableScheduledFuture, for the
* sole purpose of ensuring that the task retains a strong reference to
* the Runnable even after cancellation.
*/
static class CustomPool extends ScheduledThreadPoolExecutor {
CustomPool(int n) { super(n); }
protected <V> RunnableScheduledFuture<V> decorateTask(
final Runnable r,
final RunnableScheduledFuture<V> task) {
return new RunnableScheduledFuture<V>() {
public void run() { System.err.println(r); task.run(); }
public boolean isPeriodic() { return task.isPeriodic(); }
public V get()
throws InterruptedException,ExecutionException
{ return task.get(); }
public V get(long x, TimeUnit y)
throws InterruptedException,ExecutionException,TimeoutException
{ return task.get(x, y); }
public boolean isDone() { return task.isDone(); }
public boolean isCancelled() { return task.isCancelled(); }
public boolean cancel(boolean x) { return task.cancel(x); }
public long getDelay(TimeUnit x) { return task.getDelay(x); }
public int compareTo(Delayed x) { return task.compareTo(x); }
};
}
}
void removeAll(ReferenceQueue<?> q, int n) throws InterruptedException {
for (int j = n; j--> 0; ) {
if (q.poll() == null) {
for (;;) {
System.gc();
if (q.remove(1000) != null)
break;
System.out.printf(
"%d/%d unqueued references remaining%n", j + 1, n);
}
}
}
check(q.poll() == null);
}
void test(String[] args) throws Throwable {
final CustomPool pool = new CustomPool(10);
final int size = 100;
final ReferenceQueue<Object> q = new ReferenceQueue<>();
final List<WeakReference<?>> refs = new ArrayList<>(size);
final List<Future<?>> futures = new ArrayList<>(size);
// Schedule custom tasks with strong references.
class Task implements Runnable {
final Object x;
Task() { refs.add(new WeakReference<>(x = new Object(), q)); }
public void run() { System.out.println(x); }
}
// Give tasks added later earlier expiration, to ensure
// multiple residents of queue head.
for (int i = size; i--> 0; )
futures.add(pool.schedule(new Task(), i + 1, TimeUnit.MINUTES));
futures.forEach(future -> future.cancel(false));
futures.clear();
pool.purge();
removeAll(q, size);
for (WeakReference<?> ref : refs) check(ref.get() == null);
pool.shutdown();
// rely on test harness to handle timeout
pool.awaitTermination(1L, TimeUnit.DAYS);
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
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 {
new GCRetention().instanceMain(args);}
void instanceMain(String[] args) throws Throwable {
try {test(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,54 @@
/*
* Copyright (c) 2008, 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.ScheduledThreadPoolExecutor;
/**
* This is not a regression test, but a stress benchmark test for
* 6602600: Fast removal of cancelled scheduled thread pool tasks
*
* This runs in the same wall clock time, but much reduced cpu time,
* with the changes for 6602600.
*/
public class Stress {
public static void main(String[] args) throws Throwable {
final CountDownLatch count = new CountDownLatch(1000);
final ScheduledThreadPoolExecutor pool =
new ScheduledThreadPoolExecutor(100);
pool.prestartAllCoreThreads();
final Runnable incTask = new Runnable() { public void run() {
count.countDown();
}};
pool.scheduleAtFixedRate(incTask, 0, 10, TimeUnit.MILLISECONDS);
count.await();
pool.shutdown();
pool.awaitTermination(1L, TimeUnit.DAYS);
}
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 2011, 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.
*/
/*
* @test
* @bug 7091003
* @summary ScheduledExecutorService never executes Runnable
* with corePoolSize of zero
* @library /test/lib
* @author Chris Hegarty
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import jdk.test.lib.Utils;
/**
* Verify that tasks can be run even with a core pool size of 0.
*/
public class ZeroCorePoolSize {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
volatile boolean taskRun;
void test(String[] args) throws Throwable {
ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(0);
Runnable task = new Runnable() {
public void run() {
taskRun = true;
}
};
check(pool.getCorePoolSize() == 0);
pool.schedule(task, 12L, MILLISECONDS);
pool.shutdown();
check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
check(pool.getCorePoolSize() == 0);
check(taskRun);
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
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 {
new ZeroCorePoolSize().instanceMain(args);}
void instanceMain(String[] args) throws Throwable {
try {test(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");}
abstract class F {abstract void f() throws Throwable;}
void THROWS(Class<? extends Throwable> k, F... fs) {
for (F f : fs)
try {f.f(); fail("Expected " + k.getName() + " not thrown");}
catch (Throwable t) {
if (k.isAssignableFrom(t.getClass())) pass();
else unexpected(t);}}
}

View file

@ -0,0 +1,142 @@
/*
* 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 Martin Buchholz 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 8022642 8065320 8129861
* @summary Ensure relative sanity when zero core threads
* @library /test/lib
* @modules java.base/java.util.concurrent:open
*/
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.lang.reflect.Field;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BooleanSupplier;
import jdk.test.lib.Utils;
public class ZeroCoreThreads {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
static long millisElapsedSince(long startTime) {
return (System.nanoTime() - startTime) / (1000L * 1000L);
}
static void spinWaitUntil(BooleanSupplier predicate, long timeoutMillis) {
long startTime = -1L;
while (!predicate.getAsBoolean()) {
if (startTime == -1L)
startTime = System.nanoTime();
else if (millisElapsedSince(startTime) > timeoutMillis)
throw new AssertionError(
String.format("timed out after %s ms", timeoutMillis));
Thread.yield();
}
}
static boolean hasWaiters(ReentrantLock lock, Condition condition) {
lock.lock();
try {
return lock.hasWaiters(condition);
} finally {
lock.unlock();
}
}
static void awaitHasWaiters(ReentrantLock lock, Condition condition,
long timeoutMillis) {
spinWaitUntil(() -> hasWaiters(lock, condition), timeoutMillis);
}
static <T> T getField(Object x, String fieldName) {
try {
Field field = x.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (T) field.get(x);
} catch (ReflectiveOperationException ex) {
throw new AssertionError(ex);
}
}
void test(String[] args) throws Throwable {
ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(0);
try {
test(p);
} finally {
p.shutdownNow();
check(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
}
}
void test(ScheduledThreadPoolExecutor p) throws Throwable {
Runnable dummy = new Runnable() { public void run() {
throw new AssertionError("shouldn't get here"); }};
BlockingQueue q = p.getQueue();
ReentrantLock lock = getField(q, "lock");
Condition available = getField(q, "available");
equal(0, p.getPoolSize());
equal(0, p.getLargestPoolSize());
equal(0L, p.getTaskCount());
equal(0L, p.getCompletedTaskCount());
p.schedule(dummy, 1L, HOURS);
// Ensure one pool thread actually waits in timed queue poll
awaitHasWaiters(lock, available, LONG_DELAY_MS);
equal(1, p.getPoolSize());
equal(1, p.getLargestPoolSize());
equal(1L, p.getTaskCount());
equal(0L, p.getCompletedTaskCount());
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
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 {
new ZeroCoreThreads().instanceMain(args);}
void instanceMain(String[] args) throws Throwable {
try {test(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");}
}