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,287 @@
/*
* Copyright (c) 2007, 2024, 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 6450200
* @summary Test proper handling of pool state changes
* @library /test/lib
* @build jdk.test.lib.RandomFactory
* @run main ConfigChanges
* @key randomness
* @author Martin Buchholz
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Supplier;
import jdk.test.lib.RandomFactory;
public class ConfigChanges {
static final ThreadGroup tg = new ThreadGroup("pool");
static final Random rnd = RandomFactory.getRandom();
static void report(ThreadPoolExecutor tpe) {
try {
System.out.printf(
"active=%d submitted=%d completed=%d queued=%d sizes=%d/%d/%d%n",
tg.activeCount(),
tpe.getTaskCount(),
tpe.getCompletedTaskCount(),
tpe.getQueue().size(),
tpe.getPoolSize(),
tpe.getCorePoolSize(),
tpe.getMaximumPoolSize());
} catch (Throwable t) { unexpected(t); }
}
static void report(String label, ThreadPoolExecutor tpe) {
System.out.printf("%10s ", label);
report(tpe);
}
static 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,
() -> es.execute(nop));
}
} catch (Throwable t) { unexpected(t); }
}
static void checkTerminated(final ThreadPoolExecutor tpe) {
try {
checkShutdown(tpe);
check(tpe.getQueue().isEmpty());
check(tpe.isTerminated());
check(! tpe.isTerminating());
equal(0, tpe.getActiveCount());
equal(0, tpe.getPoolSize());
equal(tpe.getTaskCount(), tpe.getCompletedTaskCount());
check(tpe.awaitTermination(0L, MINUTES));
} catch (Throwable t) { unexpected(t); }
}
static Runnable waiter(final CyclicBarrier barrier) {
return new Runnable() { public void run() {
try { barrier.await(); barrier.await(); }
catch (Throwable t) { unexpected(t); }}};
}
static volatile Runnable runnableDuJour;
static void awaitIdleness(ThreadPoolExecutor tpe, long taskCount) {
restart: for (;;) {
// check twice to make chance of race vanishingly small
for (int i = 0; i < 2; i++) {
if (tpe.getQueue().size() != 0 ||
tpe.getActiveCount() != 0 ||
tpe.getCompletedTaskCount() != taskCount) {
Thread.yield();
continue restart;
}
}
return;
}
}
/**
* Waits for condition to become true, first spin-polling, then sleep-polling.
*/
static void spinAwait(Supplier<Boolean> waitingForGodot) {
for (int spins = 0; !waitingForGodot.get(); ) {
if ((spins = (spins + 1) & 3) > 0) {
Thread.yield();
} else {
try { Thread.sleep(4); }
catch (InterruptedException unexpected) {
throw new AssertionError(unexpected);
}
}
}
}
private static void realMain(String[] args) throws Throwable {
final boolean prestart = rnd.nextBoolean();
final Thread.UncaughtExceptionHandler handler
= new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
check(! Thread.currentThread().isInterrupted());
unexpected(e);
}};
final int n = 3;
final ThreadPoolExecutor tpe
= new ThreadPoolExecutor(n, 3*n,
3L, MINUTES,
new ArrayBlockingQueue<Runnable>(3*n));
tpe.setThreadFactory(new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = new Thread(tg, r);
t.setUncaughtExceptionHandler(handler);
return t;
}});
if (prestart) {
tpe.prestartAllCoreThreads();
equal(n, tg.activeCount());
equal(n, tpe.getCorePoolSize());
equal(n, tpe.getLargestPoolSize());
}
final Runnable runRunnableDuJour =
new Runnable() { public void run() {
// Delay choice of action till last possible moment.
runnableDuJour.run(); }};
final CyclicBarrier pumpedUp = new CyclicBarrier(3*n + 1);
runnableDuJour = waiter(pumpedUp);
if (prestart) {
for (int i = 0; i < 1*n; i++)
tpe.execute(runRunnableDuJour);
// Wait for prestarted threads to dequeue their initial tasks.
while (! tpe.getQueue().isEmpty())
Thread.sleep(1);
for (int i = 0; i < 5*n; i++)
tpe.execute(runRunnableDuJour);
} else {
for (int i = 0; i < 6*n; i++)
tpe.execute(runRunnableDuJour);
}
//report("submitted", tpe);
pumpedUp.await();
equal(3*n, tg.activeCount());
equal(3*n, tpe.getMaximumPoolSize());
equal(3*n, tpe.getLargestPoolSize());
equal(n, tpe.getCorePoolSize());
equal(3*n, tpe.getActiveCount());
equal(6L*n, tpe.getTaskCount());
equal(0L, tpe.getCompletedTaskCount());
//report("pumped up", tpe);
tpe.setMaximumPoolSize(4*n);
equal(4*n, tpe.getMaximumPoolSize());
//report("pumped up2", tpe);
final CyclicBarrier pumpedUp2 = new CyclicBarrier(n + 1);
runnableDuJour = waiter(pumpedUp2);
for (int i = 0; i < 1*n; i++)
tpe.execute(runRunnableDuJour);
pumpedUp2.await();
equal(4*n, tg.activeCount());
equal(4*n, tpe.getMaximumPoolSize());
equal(4*n, tpe.getLargestPoolSize());
equal(4*n, tpe.getActiveCount());
equal(7L*n, tpe.getTaskCount());
equal(0L, tpe.getCompletedTaskCount());
//report("pumped up2", tpe);
runnableDuJour = new Runnable() { public void run() {}};
tpe.setMaximumPoolSize(2*n);
//report("after setMaximumPoolSize", tpe);
pumpedUp2.await();
pumpedUp.await();
spinAwait(() -> tg.activeCount() == 2*n);
equal(2*n, tpe.getMaximumPoolSize());
equal(4*n, tpe.getLargestPoolSize());
//report("draining", tpe);
awaitIdleness(tpe, 7L*n);
equal(2*n, tg.activeCount());
equal(2*n, tpe.getMaximumPoolSize());
equal(4*n, tpe.getLargestPoolSize());
equal(7L*n, tpe.getTaskCount());
equal(7L*n, tpe.getCompletedTaskCount());
equal(0, tpe.getActiveCount());
equal(3L, tpe.getKeepAliveTime(MINUTES));
long t0 = System.nanoTime();
tpe.setKeepAliveTime(7L, MILLISECONDS);
equal(7L, tpe.getKeepAliveTime(MILLISECONDS));
spinAwait(() -> tg.activeCount() == n);
check(System.nanoTime() - t0 >= tpe.getKeepAliveTime(NANOSECONDS));
//report("idle", tpe);
check(! tpe.allowsCoreThreadTimeOut());
t0 = System.nanoTime();
tpe.allowCoreThreadTimeOut(true);
check(tpe.allowsCoreThreadTimeOut());
spinAwait(() -> tg.activeCount() == 0);
// The following assertion is almost always true, but may
// exceptionally not be during a transition from core count
// too high to allowCoreThreadTimeOut. Users will never
// notice, and we accept the small loss of testability.
//
// check(System.nanoTime() - t0 >= tpe.getKeepAliveTime(NANOSECONDS));
//report("idle", tpe);
tpe.shutdown();
checkShutdown(tpe);
check(tpe.awaitTermination(3L, MINUTES));
checkTerminated(tpe);
}
//--------------------- 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) {if (cond) pass(); else fail();}
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");}
interface Fun {void f() throws Throwable;}
static void THROWS(Class<? extends Throwable> k, Fun... fs) {
for (Fun 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,121 @@
/*
* Copyright (c) 2005, 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 6233235 6268386
* @summary Test allowsCoreThreadTimeOut
* @library /test/lib
* @author Martin Buchholz
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import jdk.test.lib.Utils;
public class CoreThreadTimeOut {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
static class IdentifiableThreadFactory implements ThreadFactory {
static ThreadFactory defaultThreadFactory
= Executors.defaultThreadFactory();
public Thread newThread(Runnable r) {
Thread t = defaultThreadFactory.newThread(r);
t.setName("CoreThreadTimeOut-" + t.getName());
return t;
}
}
int countExecutorThreads() {
Thread[] threads = new Thread[Thread.activeCount()+100];
Thread.enumerate(threads);
int count = 0;
for (Thread t : threads)
if (t != null &&
t.getName().matches
("CoreThreadTimeOut-pool-[0-9]+-thread-[0-9]+"))
count++;
return count;
}
static long millisElapsedSince(long startTime) {
return (System.nanoTime() - startTime) / (1000L * 1000L);
}
void test(String[] args) throws Throwable {
final int threadCount = 10;
final int timeoutMillis = 30;
BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(2*threadCount);
ThreadPoolExecutor tpe
= new ThreadPoolExecutor(threadCount, threadCount,
timeoutMillis, TimeUnit.MILLISECONDS,
q, new IdentifiableThreadFactory());
equal(tpe.getCorePoolSize(), threadCount);
check(! tpe.allowsCoreThreadTimeOut());
tpe.allowCoreThreadTimeOut(true);
check(tpe.allowsCoreThreadTimeOut());
equal(countExecutorThreads(), 0);
long startTime = System.nanoTime();
for (int i = 0; i < threadCount; i++) {
tpe.submit(() -> {});
int count = countExecutorThreads();
if (millisElapsedSince(startTime) < timeoutMillis)
equal(count, i + 1);
}
while (countExecutorThreads() > 0 &&
millisElapsedSince(startTime) < LONG_DELAY_MS)
Thread.yield();
equal(countExecutorThreads(), 0);
check(millisElapsedSince(startTime) >= timeoutMillis);
tpe.shutdown();
check(tpe.allowsCoreThreadTimeOut());
check(tpe.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new Exception("Some tests failed");
}
//--------------------- 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 CoreThreadTimeOut().instanceMain(args);}
public 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,146 @@
/*
* Copyright (c) 2005, 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 6277663
* @summary Test TPE extensibility framework
* @library /test/lib
* @author Martin Buchholz
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import jdk.test.lib.Utils;
public class Custom {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
static volatile int passed = 0, failed = 0;
static void pass() { passed++; }
static void fail() { failed++; Thread.dumpStack(); }
static void unexpected(Throwable t) { failed++; t.printStackTrace(); }
static void check(boolean cond) { if (cond) pass(); else fail(); }
static void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else {System.out.println(x + " not equal to " + y); fail(); }}
private static class CustomTask<V> extends FutureTask<V> {
public static final AtomicInteger births = new AtomicInteger(0);
CustomTask(Callable<V> c) { super(c); births.getAndIncrement(); }
CustomTask(Runnable r, V v) { super(r, v); births.getAndIncrement(); }
}
private static class CustomTPE extends ThreadPoolExecutor {
CustomTPE() {
super(threadCount, threadCount,
30, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(2*threadCount));
}
protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
return new CustomTask<V>(c);
}
protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
return new CustomTask<V>(r, v);
}
}
private static class CustomSTPE extends ScheduledThreadPoolExecutor {
public static final AtomicInteger decorations = new AtomicInteger(0);
CustomSTPE() {
super(threadCount);
}
protected <V> RunnableScheduledFuture<V> decorateTask(
Runnable r, RunnableScheduledFuture<V> task) {
decorations.getAndIncrement();
return task;
}
protected <V> RunnableScheduledFuture<V> decorateTask(
Callable<V> c, RunnableScheduledFuture<V> task) {
decorations.getAndIncrement();
return task;
}
}
static int countExecutorThreads() {
Thread[] threads = new Thread[Thread.activeCount()+100];
Thread.enumerate(threads);
int count = 0;
for (Thread t : threads)
if (t != null && t.getName().matches("pool-[0-9]+-thread-[0-9]+"))
count++;
return count;
}
private static final int threadCount = 10;
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();
}
}
public static void main(String[] args) throws Throwable {
CustomTPE tpe = new CustomTPE();
equal(tpe.getCorePoolSize(), threadCount);
equal(countExecutorThreads(), 0);
for (int i = 0; i < threadCount; i++)
tpe.submit(new Runnable() { public void run() {}});
equal(countExecutorThreads(), threadCount);
equal(CustomTask.births.get(), threadCount);
tpe.shutdown();
tpe.awaitTermination(LONG_DELAY_MS, MILLISECONDS);
spinWaitUntil(() -> countExecutorThreads() == 0, LONG_DELAY_MS);
CustomSTPE stpe = new CustomSTPE();
for (int i = 0; i < threadCount; i++)
stpe.submit(new Runnable() { public void run() {}});
equal(CustomSTPE.decorations.get(), threadCount);
equal(countExecutorThreads(), threadCount);
stpe.shutdown();
stpe.awaitTermination(LONG_DELAY_MS, MILLISECONDS);
spinWaitUntil(() -> countExecutorThreads() == 0, LONG_DELAY_MS);
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new Exception("Some tests failed");
}
}

View file

@ -0,0 +1,119 @@
/*
* 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 and 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
* @summary Should be able to shutdown a pool when worker creation failed.
* @library /test/lib
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import jdk.test.lib.Utils;
public class FlakyThreadFactory {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
void test(String[] args) throws Throwable {
test(NullPointerException.class,
new ThreadFactory() {
public Thread newThread(Runnable r) {
throw new NullPointerException();
}});
test(OutOfMemoryError.class,
new ThreadFactory() {
@SuppressWarnings("DeadThread")
public Thread newThread(Runnable r) {
// We expect this to throw OOME, but ...
new Thread(null, r, "a natural OOME", 1L << 60);
// """On some platforms, the value of the stackSize
// parameter may have no effect whatsoever."""
throw new OutOfMemoryError("artificial OOME");
}});
test(null,
new ThreadFactory() {
public Thread newThread(Runnable r) {
return null;
}});
}
void test(final Class<?> exceptionClass,
final ThreadFactory failingThreadFactory)
throws Throwable {
ThreadFactory flakyThreadFactory = new ThreadFactory() {
int seq = 0;
public Thread newThread(Runnable r) {
if (seq++ < 4)
return new Thread(r);
else
return failingThreadFactory.newThread(r);
}};
ThreadPoolExecutor pool =
new ThreadPoolExecutor(10, 10,
0L, TimeUnit.SECONDS,
new LinkedBlockingQueue(),
flakyThreadFactory);
try {
for (int i = 0; i < 8; i++)
pool.submit(new Runnable() { public void run() {} });
check(exceptionClass == null);
} catch (Throwable t) {
/* t.printStackTrace(); */
check(exceptionClass.isInstance(t));
}
pool.shutdown();
check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
}
//--------------------- 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 FlakyThreadFactory().instanceMain(args);}
public 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,77 @@
/*
* 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 6522773
* @summary Test changes to STPE core pool size
* @author Martin Buchholz
*/
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ModifyCorePoolSize {
static void awaitPoolSize(ThreadPoolExecutor pool, int n) {
while (pool.getPoolSize() != n) Thread.yield();
pass();
}
static void setCorePoolSize(ThreadPoolExecutor pool, int n) {
pool.setCorePoolSize(n);
equal(pool.getCorePoolSize(), n);
awaitPoolSize(pool, n);
}
static void realMain(String[] args) throws Throwable {
final int size = 10;
final ScheduledThreadPoolExecutor pool
= new ScheduledThreadPoolExecutor(size);
final Runnable nop = new Runnable() { public void run() {}};
for (int i = 0; i < size; i++)
pool.scheduleAtFixedRate(nop, 100L * (i + 1),
1000L, TimeUnit.MILLISECONDS);
awaitPoolSize(pool, size);
setCorePoolSize(pool, size - 3);
setCorePoolSize(pool, size + 3);
pool.shutdownNow();
check(pool.awaitTermination(1L, TimeUnit.DAYS));
}
//--------------------- 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) {if (cond) pass(); else fail();}
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,195 @@
/*
* Copyright (c) 2006, 2010, 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 6362121
* @summary Test one ScheduledThreadPoolExecutor extension scenario
* @author Martin Buchholz
*/
// based on a test kindly provided by Holger Hoffstaette <holger@wizards.de>
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class ScheduledTickleService {
// We get intermittent ClassCastException if greater than 1
// because of calls to compareTo
private static final int concurrency = 2;
// Record when tasks are done
public static final CountDownLatch done = new CountDownLatch(concurrency);
public static void realMain(String... args) throws InterruptedException {
// our tickle service
ScheduledExecutorService tickleService =
new ScheduledThreadPoolExecutor(concurrency) {
// We override decorateTask() to return a custom
// RunnableScheduledFuture which explicitly removes
// itself from the queue after cancellation.
protected <V> RunnableScheduledFuture<V>
decorateTask(Runnable runnable,
RunnableScheduledFuture<V> task) {
final ScheduledThreadPoolExecutor exec = this;
return new CustomRunnableScheduledFuture<V>(task) {
// delegate to wrapped task, except for:
public boolean cancel(boolean b) {
// cancel wrapped task & remove myself from the queue
return (task().cancel(b)
&& exec.remove(this));}};}};
for (int i = 0; i < concurrency; i++)
new ScheduledTickle(i, tickleService)
.setUpdateInterval(25, MILLISECONDS);
done.await();
tickleService.shutdown();
pass();
}
// our Runnable
static class ScheduledTickle implements Runnable {
public volatile int failures = 0;
// my tickle service
private final ScheduledExecutorService service;
// remember my own scheduled ticket
private ScheduledFuture ticket = null;
// remember the number of times I've been tickled
private int numTickled = 0;
// my private name
private final String name;
public ScheduledTickle(int i, ScheduledExecutorService service) {
super();
this.name = "Tickler-"+i;
this.service = service;
}
// set my tickle interval; 0 to disable further tickling.
public synchronized void setUpdateInterval(long interval,
TimeUnit unit) {
// cancel & remove previously created ticket
if (ticket != null) {
ticket.cancel(false);
ticket = null;
}
if (interval > 0 && ! service.isShutdown()) {
// requeue with new interval
ticket = service.scheduleAtFixedRate(this, interval,
interval, unit);
}
}
public synchronized void run() {
try {
check(numTickled < 6);
numTickled++;
System.out.println(name + ": Run " + numTickled);
// tickle 3 times and then slow down
if (numTickled == 3) {
System.out.println(name + ": slower please!");
this.setUpdateInterval(100, MILLISECONDS);
}
// ..but only 5 times max.
else if (numTickled == 5) {
System.out.println(name + ": OK that's enough.");
this.setUpdateInterval(0, MILLISECONDS);
ScheduledTickleService.done.countDown();
}
} catch (Throwable t) { unexpected(t); }
}
}
// This is just a generic wrapper to make up for the private ScheduledFutureTask
static class CustomRunnableScheduledFuture<V>
implements RunnableScheduledFuture<V> {
// the wrapped future
private RunnableScheduledFuture<V> task;
public CustomRunnableScheduledFuture(RunnableScheduledFuture<V> task) {
super();
this.task = task;
}
public RunnableScheduledFuture<V> task() { return task; }
// Forwarding methods
public boolean isPeriodic() { return task.isPeriodic(); }
public boolean isCancelled() { return task.isCancelled(); }
public boolean isDone() { return task.isDone(); }
public boolean cancel(boolean b) { return task.cancel(b); }
public long getDelay(TimeUnit unit) { return task.getDelay(unit); }
public void run() { task.run(); }
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 int compareTo(Delayed other) {
if (this == other)
return 0;
else if (other instanceof CustomRunnableScheduledFuture)
return task.compareTo(((CustomRunnableScheduledFuture)other).task());
else
return task.compareTo(other);
}
}
//--------------------- 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) {if (cond) pass(); else fail();}
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,86 @@
/*
* Copyright (c) 2007, 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 6576792
* @summary non-idle worker threads should not be interrupted
* @library /test/lib
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import jdk.test.lib.Utils;
public class SelfInterrupt {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
void test(String[] args) throws Throwable {
final int n = 100;
final ThreadPoolExecutor pool =
new ThreadPoolExecutor(n, n, 1L, TimeUnit.NANOSECONDS,
new SynchronousQueue<Runnable>());
final CountDownLatch startingGate = new CountDownLatch(n);
final CountDownLatch finishLine = new CountDownLatch(n);
equal(pool.getCorePoolSize(), n);
equal(pool.getPoolSize(), 0);
for (int i = 0; i < n; i++)
pool.execute(new Runnable() { public void run() {
try {
startingGate.countDown();
startingGate.await();
equal(pool.getPoolSize(), n);
pool.setCorePoolSize(n);
pool.setCorePoolSize(1);
check(! Thread.interrupted());
equal(pool.getPoolSize(), n);
finishLine.countDown();
finishLine.await();
check(! Thread.interrupted());
} catch (Throwable t) { unexpected(t); }}});
finishLine.await();
pool.shutdown();
check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
}
//--------------------- 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 SelfInterrupt().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,90 @@
/*
* Copyright (c) 2007, 2014, 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 6523756
* @summary Race task submission against shutdownNow
* @author Martin Buchholz
*/
// For extra chances to detect shutdownNow vs. execute races,
// crank up the iterations to, say 1<<22 and
// add a call to Thread.yield() before the call to t.start()
// in ThreadPoolExecutor.addWorker.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ShutdownNowExecuteRace {
static volatile boolean quit = false;
static volatile ThreadPoolExecutor pool = null;
static final Runnable sleeper = new Runnable() { public void run() {
final long ONE_HOUR = 1000L * 60L * 60L;
try { Thread.sleep(ONE_HOUR); }
catch (InterruptedException ie) {}
catch (Throwable t) { unexpected(t); }}};
static void realMain(String[] args) throws Throwable {
final int iterations = 1 << 8;
Thread thread = new Thread() { public void run() {
while (! quit) {
ThreadPoolExecutor pool = ShutdownNowExecuteRace.pool;
if (pool != null)
try { pool.execute(sleeper); }
catch (RejectedExecutionException e) {/* OK */}
catch (Throwable t) { unexpected(t); }}}};
thread.start();
for (int i = 0; i < iterations; i++) {
pool = new ThreadPoolExecutor(
10, 10, 3L, TimeUnit.DAYS,
new ArrayBlockingQueue<Runnable>(10));
pool.shutdownNow();
check(pool.awaitTermination(3L, TimeUnit.MINUTES));
}
quit = true;
thread.join();
}
//--------------------- 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) {if (cond) pass(); else fail();}
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");}
private abstract static class CheckedThread extends Thread {
abstract void realRun() throws Throwable;
public void run() {
try {realRun();} catch (Throwable t) {unexpected(t);}}}
}

View file

@ -0,0 +1,90 @@
/*
* 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 and Jason Mehrens 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 Only one thread should be created when a thread needs to
* be kept alive to service a delayed task waiting in the queue.
* @library /test/lib
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import jdk.test.lib.Utils;
public class ThreadRestarts {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
static final long FAR_FUTURE_MS = 10 * LONG_DELAY_MS;
public static void main(String[] args) throws Exception {
test(false);
test(true);
}
private static void test(boolean allowTimeout) throws Exception {
CountingThreadFactory ctf = new CountingThreadFactory();
ScheduledThreadPoolExecutor stpe
= new ScheduledThreadPoolExecutor(10, ctf);
try {
// schedule a dummy task in the "far future"
Runnable nop = new Runnable() { public void run() {}};
stpe.schedule(nop, FAR_FUTURE_MS, MILLISECONDS);
stpe.setKeepAliveTime(1L, MILLISECONDS);
stpe.allowCoreThreadTimeOut(allowTimeout);
MILLISECONDS.sleep(12L);
} finally {
stpe.shutdownNow();
if (!stpe.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
throw new AssertionError("timed out");
}
if (ctf.count.get() > 1)
throw new AssertionError(
String.format("%d threads created, 1 expected",
ctf.count.get()));
}
static class CountingThreadFactory implements ThreadFactory {
final AtomicLong count = new AtomicLong(0L);
public Thread newThread(Runnable r) {
count.getAndIncrement();
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
}
}

View file

@ -0,0 +1,284 @@
/*
* Copyright (c) 2007, 2024, 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 6450200 6450205 6450207 6450211
* @summary Test proper handling of tasks that terminate abruptly
* @author Martin Buchholz
* @run main ThrowingTasks
*/
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
public class ThrowingTasks {
static final Random rnd = new Random();
@SuppressWarnings("serial")
static class UncaughtExceptions
extends ConcurrentHashMap<Class<?>, Integer> {
void inc(Class<?> key) {
compute(key, (k, v) -> (v == null) ? 1 : v + 1);
}
}
/** Double-check that HashTable and ConcurrentHashMap are work-alikes. */
@SuppressWarnings("serial")
static class UncaughtExceptionsTable
extends Hashtable<Class<?>, Integer> {
synchronized void inc(Class<?> key) {
Integer v = get(key);
put(key, (v == null) ? 1 : v + 1);
}
}
static final UncaughtExceptions uncaughtExceptions
= new UncaughtExceptions();
static final UncaughtExceptionsTable uncaughtExceptionsTable
= new UncaughtExceptionsTable();
static final AtomicInteger totalUncaughtExceptions
= new AtomicInteger(0);
static final CountDownLatch uncaughtExceptionsLatch
= new CountDownLatch(24);
static final ThreadGroup tg = new ThreadGroup("Flaky");
static final RuntimeException rte = new RuntimeException();
static final Error error = new Error();
static final Throwable weird = new Throwable();
static final Exception checkedException = new Exception();
static class Thrower implements Runnable {
final Throwable t;
Thrower(Throwable t) { this.t = t; }
public void run() {
if (t != null)
ThrowingTasks.<RuntimeException>uncheckedThrow(t);
}
}
static final List<Thrower> throwers = Arrays.asList(
new Thrower(null),
new Thrower(rte),
new Thrower(error),
new Thrower(weird),
new Thrower(checkedException));
static class Flaky implements Runnable {
final Runnable beforeExecute;
final Runnable execute;
Flaky(Runnable beforeExecute,
Runnable execute) {
this.beforeExecute = beforeExecute;
this.execute = execute;
}
public void run() { execute.run(); }
}
static final List<Flaky> flakes = new ArrayList<>();
static {
for (Thrower x : throwers)
for (Thrower y : throwers)
flakes.add(new Flaky(x, y));
Collections.shuffle(flakes);
}
static final CountDownLatch allStarted = new CountDownLatch(flakes.size());
static final CountDownLatch allContinue = new CountDownLatch(1);
static void checkTerminated(ThreadPoolExecutor tpe) {
try {
check(tpe.getQueue().isEmpty());
check(tpe.isShutdown());
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); }
}
/**
* Waits for condition to become true, first spin-polling, then sleep-polling.
*/
static void spinAwait(Supplier<Boolean> waitingForGodot) {
for (int spins = 0; !waitingForGodot.get(); ) {
if ((spins = (spins + 1) & 3) > 0) {
Thread.yield();
} else {
try { Thread.sleep(4); }
catch (InterruptedException unexpected) {
throw new AssertionError(unexpected);
}
}
}
}
static class CheckingExecutor extends ThreadPoolExecutor {
private final ReentrantLock lock = new ReentrantLock();
CheckingExecutor() {
super(10, 10,
1L, TimeUnit.HOURS,
new LinkedBlockingQueue<Runnable>(),
(ThreadFactory) (runnable) -> {
Thread thread = new Thread(tg, runnable);
Thread.UncaughtExceptionHandler handler = (t, e) -> {
check(! t.isInterrupted());
totalUncaughtExceptions.getAndIncrement();
uncaughtExceptions.inc(e.getClass());
uncaughtExceptionsTable.inc(e.getClass());
uncaughtExceptionsLatch.countDown();
};
thread.setUncaughtExceptionHandler(handler);
return thread;
});
}
@Override protected void beforeExecute(Thread t, Runnable r) {
final boolean lessThanCorePoolSize;
// Add a lock to sync allStarted.countDown() and
// allStarted.getCount() < getCorePoolSize()
lock.lock();
try {
allStarted.countDown();
lessThanCorePoolSize = allStarted.getCount() < getCorePoolSize();
} finally {
lock.unlock();
}
if (lessThanCorePoolSize) {
try { allContinue.await(); }
catch (InterruptedException x) { unexpected(x); }
}
beforeExecuteCount.getAndIncrement();
check(! isTerminated());
((Flaky)r).beforeExecute.run();
}
@Override protected void afterExecute(Runnable r, Throwable t) {
//System.out.println(tg.activeCount());
afterExecuteCount.getAndIncrement();
check(((Thrower)((Flaky)r).execute).t == t);
check(! isTerminated());
}
@Override protected void terminated() {
try {
terminatedCount.getAndIncrement();
if (rnd.nextBoolean()) {
check(isShutdown());
check(isTerminating());
check(! isTerminated());
check(! awaitTermination(0L, TimeUnit.MINUTES));
}
} catch (Throwable t) { unexpected(t); }
}
}
static final AtomicInteger beforeExecuteCount = new AtomicInteger(0);
static final AtomicInteger afterExecuteCount = new AtomicInteger(0);
static final AtomicInteger terminatedCount = new AtomicInteger(0);
private static void realMain(String[] args) throws Throwable {
CheckingExecutor tpe = new CheckingExecutor();
for (Runnable task : flakes)
tpe.execute(task);
if (rnd.nextBoolean()) {
allStarted.await();
equal(tpe.getTaskCount(),
(long) flakes.size());
equal(tpe.getCompletedTaskCount(),
(long) flakes.size() - tpe.getCorePoolSize());
}
allContinue.countDown();
//System.out.printf("thread count = %d%n", tg.activeCount());
uncaughtExceptionsLatch.await();
spinAwait(() -> tg.activeCount() == tpe.getCorePoolSize());
tpe.shutdown();
check(tpe.awaitTermination(10L, TimeUnit.MINUTES));
checkTerminated(tpe);
List<Map<Class<?>, Integer>> maps = new ArrayList<>();
maps.add(uncaughtExceptions);
maps.add(uncaughtExceptionsTable);
for (Map<Class<?>, Integer> map : maps) {
equal(map.get(Exception.class), throwers.size() + 1);
equal(map.get(weird.getClass()), throwers.size() + 1);
equal(map.get(Error.class), throwers.size() + 1);
equal(map.get(RuntimeException.class), throwers.size() + 1);
equal(map.size(), 4);
}
equal(totalUncaughtExceptions.get(), 4*throwers.size() + 4);
equal(beforeExecuteCount.get(), flakes.size());
equal(afterExecuteCount.get(), throwers.size());
equal(tpe.getCompletedTaskCount(), (long) flakes.size());
equal(terminatedCount.get(), 1);
// check for termination operation idempotence
tpe.shutdown();
tpe.shutdownNow();
check(tpe.awaitTermination(10L, TimeUnit.MINUTES));
checkTerminated(tpe);
equal(terminatedCount.get(), 1);
}
//--------------------- 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) {if (cond) pass(); else fail();}
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");}
@SuppressWarnings("unchecked")
static <T extends Throwable> void uncheckedThrow(Throwable t) throws T {
throw (T)t; // rely on vacuous cast
}
}

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 2007, 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 6458662
* @summary poolSize might shrink below corePoolSize after timeout
* @library /test/lib
* @author Martin Buchholz
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import jdk.test.lib.Utils;
public class TimeOutShrink {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
static final long KEEPALIVE_MS = 12L;
static void checkPoolSizes(ThreadPoolExecutor pool,
int size, int core, int max) {
equal(pool.getPoolSize(), size);
equal(pool.getCorePoolSize(), core);
equal(pool.getMaximumPoolSize(), max);
}
private static void realMain(String[] args) throws Throwable {
final int n = 4;
final CyclicBarrier barrier = new CyclicBarrier(2*n+1);
final ThreadPoolExecutor pool
= new ThreadPoolExecutor(n, 2*n,
KEEPALIVE_MS, MILLISECONDS,
new SynchronousQueue<Runnable>());
final Runnable r = new Runnable() { public void run() {
try {
barrier.await();
barrier.await();
} catch (Throwable t) { unexpected(t); }}};
for (int i = 0; i < 2*n; i++)
pool.execute(r);
barrier.await();
checkPoolSizes(pool, 2*n, n, 2*n);
barrier.await();
long nap = KEEPALIVE_MS + (KEEPALIVE_MS >> 2);
for (long sleepyTime = 0L; pool.getPoolSize() > n; ) {
check((sleepyTime += nap) <= LONG_DELAY_MS);
Thread.sleep(nap);
}
checkPoolSizes(pool, n, n, 2*n);
Thread.sleep(nap);
checkPoolSizes(pool, n, n, 2*n);
pool.shutdown();
check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
}
//--------------------- 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) {if (cond) pass(); else fail();}
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");}
}