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,149 @@
/*
* Copyright (c) 1997, 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
* @summary Basic functional test of reference objects
* @author Mark Reinhold
*/
import java.lang.ref.*;
import java.util.Vector;
public class Basic {
static ReferenceQueue q = new ReferenceQueue();
static ReferenceQueue q2 = new ReferenceQueue();
static Reference rw, rw2, rp, rp2;
static Vector keep = new Vector();
static boolean finalized = false;
public static class ClearFinalizerThread {
protected void finalize() {
System.err.println("Cleared finalizer thread");
}
};
protected void finalize() {
System.err.println("Finalized " + this);
Basic.finalized = true;
}
public static class Sub { };
Object sub = new Sub();
static void fork(Runnable proc) throws InterruptedException {
Thread t = new Thread(proc);
t.start();
t.join();
}
static void showReferences() throws InterruptedException {
fork(new Runnable() {
public void run() {
System.err.println("References: W " + rw.get()
+ ", W2 " + rw2.get()
+ ", P " + rp.get()
+ ", P2 " + rp2.get());
}
});
}
static void createNoise() throws InterruptedException {
fork(new Runnable() {
public void run() {
keep.addElement(new PhantomReference(new Object(), q2));
}
});
}
public static void main(String[] args) throws Exception {
fork(new Runnable() {
public void run() {
Basic s = new Basic();
rw = new WeakReference(s, q);
rw2 = new WeakReference(s);
rp = new PhantomReference(s, q);
rp2 = new PhantomReference(s.sub, q);
s = null;
}
});
showReferences();
int ndq = 0;
boolean prevFinalized = false;
outer:
for (int i = 1;; i++) {
Reference r;
createNoise();
System.err.println("GC " + i);
Thread.sleep(10);
System.gc();
System.runFinalization();
showReferences();
while ((r = q2.poll()) != null) {
System.err.println("Noise " + r);
}
/* Cause a dummy object to be finalized, since the finalizer thread
might retain a reference to the Basic instance after it's been
finalized (this happens with java_g) */
if (Basic.finalized && !prevFinalized) {
fork(new Runnable() {
public void run() {
new ClearFinalizerThread();
}});
prevFinalized = true;
}
while ((r = q.poll()) != null) {
ndq++;
if (r != null) {
System.err.println("Dequeued " + r);
if (ndq == 3) break outer;
}
}
if (i >= 10) break;
}
if (ndq != 3) {
throw new Exception("Expected to dequeue 3 reference objects,"
+ " but only got " + ndq);
}
if (! Basic.finalized) {
throw new Exception("Test object not finalized");
}
}
}

View file

@ -0,0 +1,571 @@
/*
* Copyright (c) 2015, 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.
*/
import java.lang.ref.Cleaner;
import java.lang.ref.Reference;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jdk.internal.ref.PhantomCleanable;
import jdk.internal.ref.CleanerFactory;
import jdk.test.whitebox.WhiteBox;
import jdk.test.lib.Utils;
import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/*
* @test
* @library /lib/testlibrary /test/lib
* @build jdk.test.whitebox.WhiteBox
* jdk.test.lib.Utils
* jdk.test.lib.Asserts
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.JDKToolLauncher
* jdk.test.lib.Platform
* jdk.test.lib.process.*
* @modules java.base/jdk.internal.misc
* java.base/jdk.internal.ref
* java.management
* @compile CleanerTest.java
* @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
* @run testng/othervm
* -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
* -verbose:gc CleanerTest
*/
@Test
public class CleanerTest {
// A common CleaningService used by the test for notifications
static final Cleaner COMMON = CleanerFactory.cleaner();
// Access to WhiteBox utilities
static final WhiteBox whitebox = WhiteBox.getWhiteBox();
@DataProvider(name = "cleanerSuppliers")
public Object[][] factories() {
Supplier<Cleaner> supplier1 = () -> Cleaner.create();
Supplier<Cleaner> supplier2 = () -> Cleaner.create(Thread.ofVirtual().factory());
return new Object[][] { { supplier1 }, { supplier2 } };
}
/**
* Test that sequences of the various actions on a Reference
* and on the Cleanable instance have the desired result.
* The test cases are generated for each of phantom, weak and soft
* references.
* The sequence of actions includes all permutations to an initial
* list of actions including clearing the ref and resulting garbage
* collection actions on the reference and explicitly performing
* the cleaning action.
*/
@Test(dataProvider = "cleanerSuppliers")
@SuppressWarnings("unchecked")
public void testCleanableActions(Supplier<Cleaner> supplier) {
Cleaner cleaner = supplier.get();
// Individually
generateCases(cleaner, c -> c.clearRef());
generateCases(cleaner, c -> c.doClean());
// Pairs
generateCases(cleaner, c -> c.doClean(), c -> c.clearRef());
CleanableCase s = setupPhantom(COMMON, cleaner);
cleaner = null;
checkCleaned(s.getSemaphore(), true, "Cleaner was cleaned");
}
/**
* Test the jdk.internal.misc APIs with sequences of the various actions
* on a Reference and on the Cleanable instance have the desired result.
* The test cases are generated for each of phantom, weak and soft
* references.
* The sequence of actions includes all permutations to an initial
* list of actions including clearing the ref and resulting garbage
* collection actions on the reference, explicitly performing
* the cleanup and explicitly clearing the cleaning action.
*/
@Test(dataProvider = "cleanerSuppliers")
@SuppressWarnings("unchecked")
public void testRefSubtypes(Supplier<Cleaner> supplier) {
Cleaner cleaner = supplier.get();
// Individually
generateCasesInternal(cleaner, c -> c.clearRef());
generateCasesInternal(cleaner, c -> c.doClean());
generateCasesInternal(cleaner, c -> c.doClear());
// Pairs
generateCasesInternal(cleaner,
c -> c.doClear(), c -> c.doClean());
// Triplets
generateCasesInternal(cleaner,
c -> c.doClear(), c -> c.doClean(), c -> c.clearRef());
generateExceptionCasesInternal(cleaner);
CleanableCase s = setupPhantom(COMMON, cleaner);
cleaner = null;
checkCleaned(s.getSemaphore(), true, "Cleaner was cleaned");
}
/**
* Generate tests using the runnables for each of phantom, weak,
* and soft references.
* @param cleaner the cleaner
* @param runnables the sequence of actions on the test case
*/
@SuppressWarnings("unchecked")
void generateCases(Cleaner cleaner, Consumer<CleanableCase>... runnables) {
generateCases(() -> setupPhantom(cleaner, null), runnables.length, runnables);
}
@SuppressWarnings("unchecked")
void generateCasesInternal(Cleaner cleaner, Consumer<CleanableCase>... runnables) {
generateCases(() -> setupPhantomSubclass(cleaner, null),
runnables.length, runnables);
}
@SuppressWarnings("unchecked")
void generateExceptionCasesInternal(Cleaner cleaner) {
generateCases(() -> setupPhantomSubclassException(cleaner, null),
1, c -> c.clearRef());
}
/**
* Generate all permutations of the sequence of runnables
* and test each one.
* The permutations are generated using Heap, B.R. (1963) Permutations by Interchanges.
* @param generator the supplier of a CleanableCase
* @param n the first index to interchange
* @param runnables the sequence of actions
*/
@SuppressWarnings("unchecked")
void generateCases(Supplier<CleanableCase> generator, int n,
Consumer<CleanableCase> ... runnables) {
if (n == 1) {
CleanableCase test = generator.get();
try {
verifyGetRef(test);
// Apply the sequence of actions on the Ref
for (Consumer<CleanableCase> c : runnables) {
c.accept(test);
}
verify(test);
} catch (Exception e) {
Assert.fail(test.toString(), e);
}
} else {
for (int i = 0; i < n - 1; i += 1) {
generateCases(generator, n - 1, runnables);
Consumer<CleanableCase> t = runnables[n - 1];
int ndx = ((n & 1) == 0) ? i : 0;
runnables[n - 1] = runnables[ndx];
runnables[ndx] = t;
}
generateCases(generator, n - 1, runnables);
}
}
/**
* Verify the test case.
* Any actions directly on the Reference or Cleanable have been executed.
* The CleanableCase under test is given a chance to do the cleanup
* by forcing a GC.
* The result is compared with the expected result computed
* from the sequence of operations on the Cleanable.
* The Cleanable itself should have been cleanedup.
*
* @param test A CleanableCase containing the references
*/
void verify(CleanableCase test) {
System.out.println(test);
int r = test.expectedResult();
CleanableCase cc = setupPhantom(COMMON, test.getCleanable());
test.clearCleanable(); // release this hard reference
checkCleaned(test.getSemaphore(),
r == CleanableCase.EV_CLEAN,
"Cleanable was cleaned");
checkCleaned(cc.getSemaphore(), true,
"The reference to the Cleanable was freed");
}
/**
* Verify that the reference.get works (or not) as expected.
* It handles the cases where UnsupportedOperationException is expected.
*
* @param test the CleanableCase
*/
void verifyGetRef(CleanableCase test) {
Reference<?> r = (Reference) test.getCleanable();
try {
Object o = r.get();
Reference<?> expectedRef = test.getRef();
Assert.assertEquals(expectedRef.get(), o,
"Object reference incorrect");
if (r.getClass().getName().endsWith("CleanableRef")) {
Assert.fail("should not be able to get referent");
}
} catch (UnsupportedOperationException uoe) {
if (r.getClass().getName().endsWith("CleanableRef")) {
// Expected exception
} else {
Assert.fail("Unexpected exception from subclassed cleanable: " +
uoe.getMessage() + ", class: " + r.getClass());
}
}
}
/**
* Test that releasing the reference to the Cleaner service allows it to be
* be freed.
*/
@Test(dataProvider = "cleanerSuppliers")
public void testCleanerTermination(Supplier<Cleaner> supplier) {
ReferenceQueue<Object> queue = new ReferenceQueue<>();
Cleaner service = supplier.get();
PhantomReference<Object> ref = new PhantomReference<>(service, queue);
System.gc();
// Clear the Reference to the cleaning service and force a gc.
service = null;
System.gc();
try {
Reference<?> r = queue.remove(1000L);
Assert.assertNotNull(r, "queue.remove timeout,");
Assert.assertEquals(r, ref, "Wrong Reference dequeued");
} catch (InterruptedException ie) {
System.out.printf("queue.remove Interrupted%n");
}
}
/**
* Check a semaphore having been released by cleanup handler.
* Force a number of GC cycles to give the GC a chance to process
* the Reference and for the cleanup action to be run.
* Use a larger number of cycles to wait for an expected cleaning to occur.
*
* @param semaphore a Semaphore
* @param expectCleaned true if cleaning the function should have been run, otherwise not run
* @param msg a message describing the cleaning function expected to be run or not run
*/
static void checkCleaned(Semaphore semaphore, boolean expectCleaned, String msg) {
long max_cycles = expectCleaned ? 10 : 3;
long cycle = 0;
for (; cycle < max_cycles; cycle++) {
// Force GC
whitebox.fullGC();
try {
if (semaphore.tryAcquire(Utils.adjustTimeout(200L), TimeUnit.MILLISECONDS)) {
System.out.printf(" Cleanable cleaned in cycle: %d%n", cycle);
if (!expectCleaned)
Assert.fail("Should not have been run: " + msg);
return;
}
} catch (InterruptedException ie) {
// retry in outer loop
}
}
// Object has not been cleaned
if (expectCleaned)
Assert.fail("Should have been run: " + msg);
}
/**
* Create a CleanableCase for a PhantomReference.
* @param cleaner the cleaner to use
* @param obj an object or null to create a new Object
* @return a new CleanableCase preset with the object, cleanup, and semaphore
*/
static CleanableCase setupPhantom(Cleaner cleaner, Object obj) {
if (obj == null) {
obj = new Object();
}
Semaphore s1 = new Semaphore(0);
Cleaner.Cleanable c1 = cleaner.register(obj, () -> s1.release());
return new CleanableCase(new PhantomReference<>(obj, null), c1, s1);
}
/**
* Create a CleanableCase for a PhantomReference.
* @param cleaner the cleaner to use
* @param obj an object or null to create a new Object
* @return a new CleanableCase preset with the object, cleanup, and semaphore
*/
static CleanableCase setupPhantomSubclass(Cleaner cleaner, Object obj) {
if (obj == null) {
obj = new Object();
}
Semaphore s1 = new Semaphore(0);
Cleaner.Cleanable c1 = new PhantomCleanable<Object>(obj, cleaner) {
protected void performCleanup() {
s1.release();
}
};
return new CleanableCase(new PhantomReference<>(obj, null), c1, s1);
}
/**
* Create a CleanableCase for a PhantomReference.
* @param cleaner the cleaner to use
* @param obj an object or null to create a new Object
* @return a new CleanableCase preset with the object, cleanup, and semaphore
*/
static CleanableCase setupPhantomSubclassException(Cleaner cleaner, Object obj) {
if (obj == null) {
obj = new Object();
}
Semaphore s1 = new Semaphore(0);
Cleaner.Cleanable c1 = new PhantomCleanable<Object>(obj, cleaner) {
protected void performCleanup() {
s1.release();
throw new RuntimeException("Exception thrown to cleaner thread");
}
};
return new CleanableCase(new PhantomReference<>(obj, null), c1, s1, true);
}
/**
* CleanableCase encapsulates the objects used for a test.
* The reference to the object is not held directly,
* but in a Reference object that can be cleared.
* The semaphore is used to count whether the cleanup occurred.
* It can be awaited on to determine that the cleanup has occurred.
* It can be checked for non-zero to determine if it was
* invoked or if it was invoked twice (a bug).
*/
static class CleanableCase {
private volatile Reference<?> ref;
private volatile Cleaner.Cleanable cleanup;
private final Semaphore semaphore;
private final boolean throwsEx;
private final int[] events; // Sequence of calls to clean, clear, etc.
private volatile int eventNdx;
public static int EV_UNKNOWN = 0;
public static int EV_CLEAR = 1;
public static int EV_CLEAN = 2;
public static int EV_UNREF = 3;
public static int EV_CLEAR_CLEANUP = 4;
CleanableCase(Reference<Object> ref, Cleaner.Cleanable cleanup,
Semaphore semaphore) {
this.ref = ref;
this.cleanup = cleanup;
this.semaphore = semaphore;
this.throwsEx = false;
this.events = new int[4];
this.eventNdx = 0;
}
CleanableCase(Reference<Object> ref, Cleaner.Cleanable cleanup,
Semaphore semaphore,
boolean throwsEx) {
this.ref = ref;
this.cleanup = cleanup;
this.semaphore = semaphore;
this.throwsEx = throwsEx;
this.events = new int[4];
this.eventNdx = 0;
}
public Reference<?> getRef() {
return ref;
}
public void clearRef() {
addEvent(EV_UNREF);
ref.clear();
}
public Cleaner.Cleanable getCleanable() {
return cleanup;
}
public void doClean() {
try {
addEvent(EV_CLEAN);
cleanup.clean();
} catch (RuntimeException ex) {
if (!throwsEx) {
// unless it is known this case throws an exception, rethrow
throw ex;
}
}
}
public void doClear() {
addEvent(EV_CLEAR);
((Reference)cleanup).clear();
}
public void clearCleanable() {
addEvent(EV_CLEAR_CLEANUP);
cleanup = null;
}
public Semaphore getSemaphore() {
return semaphore;
}
public boolean isCleaned() {
return semaphore.availablePermits() != 0;
}
private synchronized void addEvent(int e) {
events[eventNdx++] = e;
}
/**
* Computed the expected result from the sequence of events.
* If EV_CLEAR appears before anything else, it is cleared.
* If EV_CLEAN appears before EV_UNREF, then it is cleaned.
* Anything else is Unknown.
* @return EV_CLEAR if the cleanup should occur;
* EV_CLEAN if the cleanup should occur;
* EV_UNKNOWN if it is unknown.
*/
public synchronized int expectedResult() {
// Test if EV_CLEAR appears before anything else
int clearNdx = indexOfEvent(EV_CLEAR);
int cleanNdx = indexOfEvent(EV_CLEAN);
int unrefNdx = indexOfEvent(EV_UNREF);
if (clearNdx < cleanNdx) {
return EV_CLEAR;
}
if (cleanNdx < clearNdx || cleanNdx < unrefNdx) {
return EV_CLEAN;
}
if (unrefNdx < eventNdx) {
return EV_CLEAN;
}
return EV_UNKNOWN;
}
private synchronized int indexOfEvent(int e) {
for (int i = 0; i < eventNdx; i++) {
if (events[i] == e) {
return i;
}
}
return eventNdx;
}
private static final String[] names =
{"UNKNOWN", "EV_CLEAR", "EV_CLEAN", "EV_UNREF", "EV_CLEAR_CLEANUP"};
public String eventName(int event) {
return names[event];
}
public synchronized String eventsString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (int i = 0; i < eventNdx; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(eventName(events[i]));
}
sb.append(']');
sb.append(", throwEx: ");
sb.append(throwsEx);
return sb.toString();
}
public String toString() {
return String.format("Case: %s, expect: %s, events: %s",
getRef().getClass().getName(),
eventName(expectedResult()), eventsString());
}
}
/**
* Verify that casting a Cleanup to a Reference is not allowed to
* get the referent or clear the reference.
*/
@Test(dataProvider = "cleanerSuppliers")
@SuppressWarnings("rawtypes")
public void testReferentNotAvailable(Supplier<Cleaner> supplier) {
Cleaner cleaner = supplier.get();
Semaphore s1 = new Semaphore(0);
Object obj = new String("a new string");
Cleaner.Cleanable c = cleaner.register(obj, () -> s1.release());
Reference r = (Reference) c;
try {
Object o = r.get();
System.out.printf("r: %s%n", Objects.toString(o));
Assert.fail("should not be able to get the referent from Cleanable");
} catch (UnsupportedOperationException uoe) {
// expected
}
try {
r.clear();
Assert.fail("should not be able to clear the referent from Cleanable");
} catch (UnsupportedOperationException uoe) {
// expected
}
obj = null;
checkCleaned(s1, true, "reference was cleaned");
cleaner = null;
}
/**
* Test the Cleaner from the CleanerFactory.
*/
@Test
public void testCleanerFactory() {
Cleaner cleaner = CleanerFactory.cleaner();
Object obj = new Object();
CleanableCase s = setupPhantom(cleaner, obj);
obj = null;
checkCleaned(s.getSemaphore(), true,
"Object cleaned using internal CleanerFactory.cleaner()");
}
}

View file

@ -0,0 +1,104 @@
/*
* Copyright (c) 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 6853696
* @summary ReferenceQueue#remove(timeout) should not return null before
* timeout is elapsed
*/
import java.lang.InterruptedException;
import java.lang.System;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.CountDownLatch;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
/**
* In order to demonstrate the issue we make several threads (two appears to be sufficient)
* to block in ReferenceQueue#remove(timeout) at the same time.
* Then, we force a reference to be enqueued by setting its referent to null and calling System.gc().
* One of the threads gets the reference returned from the remove().
* The other threads get null:
* 1) with bug: this may happen before the specified timeout is elapsed,
* 2) without bug: this can only happen after the timeout is fully elapsed.
*/
public class EarlyTimeout extends Thread {
static final int THREADS_COUNT = 2;
static final int TIMEOUT = 1000;
static Object referent = new Object();
static final ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
static final WeakReference<Object> weakReference = new WeakReference<Object>(referent, queue);
static final CountDownLatch startedSignal = new CountDownLatch(THREADS_COUNT);
long actual;
Reference<?> reference;
public static void main(String[] args) throws Exception {
EarlyTimeout[] threads = new EarlyTimeout[THREADS_COUNT];
for (int i = 0; i < THREADS_COUNT; ++i) {
threads[i] = new EarlyTimeout();
threads[i].start();
}
// The main thread waits until the threads has started and give it a chance
// for the threads to block on the queue.remove(TIMEOUT) call
startedSignal.await();
Thread.sleep(TIMEOUT / 2);
referent = null;
System.gc();
for (EarlyTimeout thread : threads) {
thread.join();
}
if (weakReference.get() != null) {
throw new RuntimeException("weakReference was not cleared");
}
int nonNullRefCount = 0;
for (EarlyTimeout thread : threads) {
if (thread.reference == null && thread.actual < TIMEOUT) {
throw new RuntimeException("elapsed time " + thread.actual
+ " is less than timeout " + TIMEOUT);
}
if (thread.reference != null && thread.reference == weakReference) {
nonNullRefCount++;
}
}
if (nonNullRefCount > 1) {
throw new RuntimeException("more than one references were removed from queue");
}
}
public void run() {
try {
startedSignal.countDown();
long start = System.nanoTime();
reference = queue.remove(TIMEOUT);
actual = NANOSECONDS.toMillis(System.nanoTime() - start);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2003, 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 4247236
* @summary Ensure that reference objects with null referents can be enqueued
*/
import java.lang.ref.*;
public class EnqueueNullRef {
static void test(ReferenceQueue q, Reference r) {
if (!r.enqueue())
throw new RuntimeException("Enqueue operation failed");
}
public static void main(String[] args) {
ReferenceQueue q = new ReferenceQueue();
test(q, new WeakReference(null, q));
test(q, new SoftReference(null, q));
test(q, new PhantomReference(null, q));
}
}

View file

@ -0,0 +1,73 @@
/*
* Copyright (c) 2013, 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 8014890
* @summary Verify that a race between ReferenceQueue.enqueue() and poll() does not occur.
* @author thomas.schatzl@oracle.com
* @run main/othervm -Xmx10M EnqueuePollRace
*/
import java.lang.ref.*;
public class EnqueuePollRace {
public static void main(String args[]) throws Exception {
new WeakRef().run();
System.out.println("Test passed.");
}
static class WeakRef {
ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
final int numReferences = 100;
final Reference refs[] = new Reference[numReferences];
final int iterations = 1000;
void run() throws InterruptedException {
for (int i = 0; i < iterations; i++) {
queue = new ReferenceQueue<Object>();
for (int j = 0; j < refs.length; j++) {
refs[j] = new WeakReference(new Object(), queue);
}
System.gc(); // enqueues references into the list of discovered references
// now manually enqueue all of them
for (int j = 0; j < refs.length; j++) {
refs[j].enqueue();
}
// and get them back. There should be exactly numReferences
// entries in the queue now.
int foundReferences = 0;
while (queue.poll() != null) {
foundReferences++;
}
if (foundReferences != refs.length) {
throw new RuntimeException("Got " + foundReferences + " references in the queue, but expected " + refs.length);
}
}
}
}
}

View file

@ -0,0 +1,180 @@
/*
* Copyright (c) 2013, 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.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicInteger;
/* @test
* @bug 8027351 8148940
* @summary Basic test of the finalize method
*/
public class FinalizeOverride {
// finalizedCount is incremented when the finalize method is invoked
private static AtomicInteger finalizedCount = new AtomicInteger();
// finalizedSum and privateFinalizedInvoke are used to verify
// the right overrided finalize method is invoked
private static AtomicInteger finalizedSum = new AtomicInteger();
private static volatile boolean privateFinalizeInvoked = false;
public static void main(String[] argvs) throws IOException {
patchPrivateFinalize();
test(new Base(10), 10);
test(new Subclass(20), 0);
test(new SubSubclass(30), 30);
test(new PublicFinalize(40), 40*100+40);
test(new PrivateFinalize(50), 50);
test(new NoOverride(60), 60);
}
static void test(Object o, int expected) {
int count = finalizedCount.get();
int sum = finalizedSum.get();
privateFinalizeInvoked = false;
// force GC and finalization
o = null;
while (finalizedCount.get() != (count+1)) {
System.gc();
System.runFinalization();
// Running System.gc() and System.runFinalization() in a
// tight loop can trigger frequent safepointing that slows
// down the VM and, as a result, the test. (With the
// HotSpot VM, the effect of frequent safepointing is
// especially noticeable if the test is run with the
// -Xcomp flag.) Sleeping for a second after every
// garbage collection and finalization cycle gives the VM
// time to make progress.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted, continuing execution.");
}
}
if (privateFinalizeInvoked) {
throw new RuntimeException("private finalize method invoked");
}
if (finalizedCount.get() != (count+1)) {
throw new RuntimeException("Unexpected count=" + finalizedCount +
" expected=" + (count+1));
}
if (finalizedSum.get() != (sum+expected)) {
throw new RuntimeException("Unexpected sum=" + finalizedSum +
" prev=" + sum + " value=" + expected);
}
}
static void patchPrivateFinalize() throws IOException {
// patch the private f_nal_ze method name to "finalize"
String testClasses = System.getProperty("test.classes", ".");
Path p = Paths.get(testClasses, "FinalizeOverride$PrivateFinalize.class");
byte[] bytes = Files.readAllBytes(p);
int len = "f_nal_ze".length();
for (int i=0; i < bytes.length-len; i++) {
if (bytes[i] == 'f' &&
bytes[i+1] == '_' &&
bytes[i+2] == 'n' &&
bytes[i+3] == 'a' &&
bytes[i+4] == 'l' &&
bytes[i+5] == '_' &&
bytes[i+6] == 'z' &&
bytes[i+7] == 'e')
{
// s%_%i%
bytes[i+1] = 'i';
bytes[i+5] = 'i';
break;
}
}
Files.write(p, bytes);
}
static class Base {
protected int value;
Base(int v) {
this.value = v;
}
int called() {
finalizedSum.addAndGet(value);
return value;
}
protected void finalize() {
System.out.println("Base.finalize() sum += " + called());
finalizedCount.incrementAndGet();
}
}
static class PublicFinalize extends Base {
PublicFinalize(int v) {
super(v);
}
public void finalize() {
finalizedSum.addAndGet(value * 100);
System.out.println("PublicFinalize.finalize() sum += " + called() +
"+"+value+"*100");
finalizedCount.incrementAndGet();
}
}
static class Subclass extends Base {
Subclass(int v) {
super(v);
}
protected void finalize() {
// no value added to sum
System.out.println("Subclass.finalize() sum += 0");
finalizedCount.incrementAndGet();
}
}
static class SubSubclass extends Subclass {
SubSubclass(int v) {
super(v);
}
protected final void finalize() {
finalizedSum.addAndGet(value);
System.out.println("SubSubclass.finalize() sum +=" +value);
finalizedCount.incrementAndGet();
}
}
static class PrivateFinalize extends Base {
PrivateFinalize(int v) {
super(v);
}
private void f_nal_ze() {
// finalization catches any exception
System.out.println("Error: private finalize invoked!!");
privateFinalizeInvoked = true;
finalizedCount.incrementAndGet();
}
}
static class NoOverride extends PrivateFinalize {
NoOverride(int v) {
super(v);
}
}
}

View file

@ -0,0 +1,118 @@
/*
* Copyright (c) 2015, 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.
*/
import jdk.test.whitebox.WhiteBox;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
/*
* @test
* @summary Unit test for FinalizerHistogram
* @modules java.base/java.lang.ref:open
* @library /test/lib
* @build jdk.test.whitebox.WhiteBox
* @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
* @run main/othervm
* -Xbootclasspath/a:.
* -XX:+UnlockDiagnosticVMOptions
* -XX:+WhiteBoxAPI
* FinalizerHistogramTest
*/
public class FinalizerHistogramTest {
static ReentrantLock lock = new ReentrantLock();
static final AtomicInteger initializedCount = new AtomicInteger(0);
static final int OBJECTS_COUNT = 1000;
static WhiteBox wb;
static class MyObject {
public MyObject() {
// Make sure object allocation/deallocation is not optimized out
initializedCount.incrementAndGet();
}
protected void finalize() {
// Trap the object in a finalization queue
lock.lock();
}
}
public static void main(String[] argvs) throws InterruptedException {
try {
lock.lock();
for(int i = 0; i < OBJECTS_COUNT; ++i) {
new MyObject();
}
System.out.println("Objects intialized: " + initializedCount.get());
wb = WhiteBox.getWhiteBox();
wb.fullGC();
boolean refProResult;
do {
refProResult = wb.waitForReferenceProcessing();
System.out.println("waitForReferenceProcessing returned: " + refProResult);
} while (refProResult);
Class<?> klass = Class.forName("java.lang.ref.FinalizerHistogram");
Method m = klass.getDeclaredMethod("getFinalizerHistogram");
m.setAccessible(true);
Object entries[] = (Object[]) m.invoke(null);
Class<?> entryKlass = Class.forName("java.lang.ref.FinalizerHistogram$Entry");
Field name = entryKlass.getDeclaredField("className");
name.setAccessible(true);
Field count = entryKlass.getDeclaredField("instanceCount");
count.setAccessible(true);
System.out.println("Unreachable instances waiting for finalization");
System.out.println("#instances class name");
System.out.println("-----------------------");
boolean found = false;
for (Object entry : entries) {
Object e = entryKlass.cast(entry);
System.out.printf("%10d %s\n", count.get(e), name.get(e));
if (((String) name.get(e)).indexOf("MyObject") != -1 ) {
found = true;
}
}
if (!found) {
throw new RuntimeException("MyObject is not found in test output");
}
System.out.println("Test PASSED");
} catch(Exception e) {
System.err.println("Test failed with " + e);
e.printStackTrace(System.err);
throw new RuntimeException("Test failed");
} finally {
lock.unlock();
}
}
}

View file

@ -0,0 +1,89 @@
/*
* Copyright (c) 1999, 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 4178693
* @summary Ensure that null queue arguments don't crash the Reference handler
* @author Mark Reinhold
*/
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
public class NullQueue {
private static Reference r = null;
private static Thread findThread(String name) {
/* Find reference-handler thread */
ThreadGroup tg = Thread.currentThread().getThreadGroup();
for (ThreadGroup tgn = tg;
tgn != null;
tg = tgn, tgn = tg.getParent());
int nt = tg.activeCount();
Thread[] ts = new Thread[nt];
tg.enumerate(ts);
Thread refHandler = null;
for (int i = 0; i < ts.length; i++) {
if (ts[i].getName().equals(name)) return ts[i];
}
return null;
}
private static void fork(Runnable proc) throws InterruptedException {
Thread t = new Thread(proc);
t.start();
t.join();
}
public static void main(String[] args) throws Exception {
Thread refHandler = findThread("Reference Handler");
if (refHandler == null)
throw new Exception("Couldn't find Reference-handler thread");
if (!refHandler.isAlive())
throw new Exception("Reference-handler thread is not alive");
/* Invoke a Reference constructor, passing null for the queue */
fork(new Runnable() {
public void run() {
r = new WeakReference(new Object(), null);
}});
/* Force the reference to be cleared and enqueued by the GC */
for (int i = 0;; i++) {
Thread.sleep(10);
System.gc();
if (r.get() == null) break;
if (i >= 10)
throw new Exception("Couldn't cause weak ref to be cleared");
}
/* Check that the handler is still alive */
if (!refHandler.isAlive())
throw new Exception("Reference-handler thread died");
}
}

View file

@ -0,0 +1,116 @@
/*
* Copyright (c) 2013, 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 7038914 8016341
* @summary Verify that the reference handler does not die after an OOME allocating the InterruptedException object
* @requires test.thread.factory == null
* @run main/othervm -XX:-UseGCOverheadLimit -Xmx24M -XX:-UseTLAB OOMEInReferenceHandler
* @author peter.levart@gmail.com
* @key intermittent
*/
import java.lang.ref.*;
public class OOMEInReferenceHandler {
static Object[] fillHeap() {
Object[] first = null, last = null;
int size = 1 << 20;
while (size > 0) {
try {
Object[] array = new Object[size];
if (first == null) {
first = array;
} else {
last[0] = array;
}
last = array;
} catch (OutOfMemoryError oome) {
size = size >>> 1;
}
}
return first;
}
public static void main(String[] args) throws Exception {
// preinitialize the InterruptedException class so that the reference handler
// does not die due to OOME when loading the class if it is the first use
InterruptedException ie = new InterruptedException("dummy");
ThreadGroup tg = Thread.currentThread().getThreadGroup();
for (
ThreadGroup tgn = tg;
tgn != null;
tg = tgn, tgn = tg.getParent()
)
;
Thread[] threads = new Thread[tg.activeCount()];
Thread referenceHandlerThread = null;
int n = tg.enumerate(threads);
for (int i = 0; i < n; i++) {
if ("Reference Handler".equals(threads[i].getName())) {
referenceHandlerThread = threads[i];
}
}
if (referenceHandlerThread == null) {
throw new IllegalStateException("Couldn't find Reference Handler thread.");
}
ReferenceQueue<Object> refQueue = new ReferenceQueue<>();
Object referent = new Object();
WeakReference<Object> weakRef = new WeakReference<>(referent, refQueue);
// Allow thread.sleep() to pre-allocate ThreadSleepEvent object
Thread.sleep(1L);
Object waste = fillHeap();
referenceHandlerThread.interrupt();
// allow referenceHandlerThread some time to throw OOME
Thread.sleep(500L);
// release waste & referent
waste = null;
referent = null;
// wait at most 10 seconds for success or failure
for (int i = 0; i < 20; i++) {
if (refQueue.poll() != null) {
// Reference Handler thread still working -> success
return;
}
System.gc();
Thread.sleep(500L); // wait a little to allow GC to do it's work before allocating objects
if (!referenceHandlerThread.isAlive()) {
// Reference Handler thread died -> failure
throw new Exception("Reference Handler thread died.");
}
}
// no sure answer after 10 seconds
throw new IllegalStateException("Reference Handler thread stuck. weakRef.get(): " + weakRef.get());
}
}

View file

@ -0,0 +1,101 @@
/*
* Copyright (c) 2015, 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 8071507
* @summary Test that PhantomReferences are cleared when notified.
* @run main/othervm PhantomReferentClearing
*/
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
public class PhantomReferentClearing {
private static final long ENQUEUE_TIMEOUT = 1000; // 1 sec, in millis
// P1 & P2 are PhantomReference objects
// O1 & O2 are objects
//
// -> is a strong reference
// => is a referent reference
//
// root -> P1
// root -> P2
// root -> O1
// root -> O2
// O1 -> O2
// P1 => O1
// P2 => O2
//
// (1) Remove root -> O1 and collect. P1 notified, P2 !notified.
// (2) Remove root -> O2 and collect.
//
// If phantom references are cleared when notified, as proposed by
// 8071507, then P2 should be notified, and the test passes.
//
// Otherwise, P2 does not get notified because it remains reachable
// from O1, which is being retained by P1. This fails the test.
private static final ReferenceQueue<Object> Q1 = new ReferenceQueue<>();
private static final ReferenceQueue<Object> Q2 = new ReferenceQueue<>();
private static volatile Object O2 = new Object();
private static volatile List<Object> O1 = new ArrayList<>();
static {
O1.add(O2);
}
private static final PhantomReference<Object> P1 = new PhantomReference<>(O1, Q1);
private static final PhantomReference<Object> P2 = new PhantomReference<>(O2, Q2);
public static void main(String[] args) throws InterruptedException {
// Collect, and verify neither P1 or P2 notified.
System.gc();
if (Q1.remove(ENQUEUE_TIMEOUT) != null) {
throw new RuntimeException("P1 already notified");
} else if (Q2.poll() != null) {
throw new RuntimeException("P2 already notified");
}
// Delete root -> O1, collect, verify P1 notified, P2 not notified.
O1 = null;
System.gc();
if (Q1.remove(ENQUEUE_TIMEOUT) == null) {
throw new RuntimeException("P1 not notified by O1 deletion");
} else if (Q2.remove(ENQUEUE_TIMEOUT) != null) {
throw new RuntimeException("P2 notified by O1 deletion.");
}
// Delete root -> O2, collect. P2 should be notified.
O2 = null;
System.gc();
if (Q2.remove(ENQUEUE_TIMEOUT) == null) {
throw new RuntimeException("P2 not notified by O2 deletion");
}
}
}

View file

@ -0,0 +1,147 @@
/*
* Copyright (c) 2015, 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 8133348
* @summary Tests if reachabilityFence is working
*
* @requires vm.opt.DeoptimizeALot != true
*
* @run main/othervm -Xint -Dpremature=false ReachabilityFenceTest
* @run main/othervm -Xbatch -XX:TieredStopAtLevel=1 -Dpremature=true ReachabilityFenceTest
* @run main/othervm -Xbatch -XX:TieredStopAtLevel=2 -Dpremature=true ReachabilityFenceTest
* @run main/othervm -Xbatch -XX:TieredStopAtLevel=3 -Dpremature=true ReachabilityFenceTest
* @run main/othervm -Xbatch -XX:TieredStopAtLevel=4 -Dpremature=true ReachabilityFenceTest
*/
import java.lang.ref.Reference;
import java.util.concurrent.atomic.AtomicBoolean;
public class ReachabilityFenceTest {
/*
* Implementation notes:
*
* This test has positive and negative parts.
*
* Negative test is "nonFenced", and it tests that absent of reachabilityFence, the object can
* be prematurely finalized -- this validates the test itself. Not every VM mode is expected to
* prematurely finalize the objects, and -Dpremature option communicates that to test. If a VM mode
* passes the negative test, then our understanding of what could happen is correct, and we can
* go forward.
*
* Positive test is "fenced", and it checks that given the reachabilityFence at the end of the block,
* the object cannot be finalized. There is no sense running a positive test when premature finalization
* is not expected. It is a job for negative test to verify that invariant.
*
* The test methods should be appropriately compiled, therefore we do several iterations and run with -Xbatch.
*/
// Enough to OSR and compile
static final int LOOP_ITERS = Integer.getInteger("LOOP_ITERS", 50000);
// Enough after which to start triggering GC and finalization
static final int WARMUP_LOOP_ITERS = LOOP_ITERS - Integer.getInteger("GC_ITERS", 100);
// Enough to switch from an OSR'ed method to compiled method
static final int MAIN_ITERS = 3;
static final boolean PREMATURE_FINALIZATION = Boolean.getBoolean("premature");
public static void main(String... args) {
// Negative test
boolean finalized = false;
for (int c = 0; !finalized && c < MAIN_ITERS; c++) {
finalized |= nonFenced();
}
if (PREMATURE_FINALIZATION && !finalized) {
throw new IllegalStateException("The object had never been finalized before timeout reached.");
}
if (!PREMATURE_FINALIZATION && finalized) {
throw new IllegalStateException("The object had been finalized without a fence, even though we don't expect it.");
}
if (!PREMATURE_FINALIZATION)
return;
// Positive test
finalized = false;
for (int c = 0; !finalized && c < MAIN_ITERS; c++) {
finalized |= fenced();
}
if (finalized) {
throw new IllegalStateException("The object had been prematurely finalized.");
}
}
public static boolean nonFenced() {
AtomicBoolean finalized = new AtomicBoolean();
MyFinalizeable o = new MyFinalizeable(finalized);
for (int i = 0; i < LOOP_ITERS; i++) {
if (finalized.get()) break;
if (i > WARMUP_LOOP_ITERS) {
System.gc();
System.runFinalization();
}
}
return finalized.get();
}
public static boolean fenced() {
AtomicBoolean finalized = new AtomicBoolean();
MyFinalizeable o = new MyFinalizeable(finalized);
for (int i = 0; i < LOOP_ITERS; i++) {
if (finalized.get()) break;
if (i > WARMUP_LOOP_ITERS) {
System.gc();
System.runFinalization();
}
}
try {
return finalized.get();
} finally {
Reference.reachabilityFence(o);
}
}
private static class MyFinalizeable {
private final AtomicBoolean finalized;
public MyFinalizeable(AtomicBoolean b) {
this.finalized = b;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
finalized.set(true);
}
}
}

View file

@ -0,0 +1,106 @@
/*
* Copyright (c) 2018, 2022, 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 8201793 8285690
* @summary Test Reference::clone to throw CloneNotSupportedException
*/
import java.lang.ref.*;
public class ReferenceClone {
private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue<>();
public static void main(String... args) {
ReferenceClone refClone = new ReferenceClone();
refClone.test();
}
public void test() {
// test Reference::clone that throws CNSE
Object o = new Object();
assertCloneNotSupported(new SoftRef(o));
assertCloneNotSupported(new WeakRef(o));
assertCloneNotSupported(new PhantomRef(o));
// Reference subclass may override the clone method
CloneableReference ref = new CloneableReference(o);
try {
ref.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("CloneableReference::clone should not throw CloneNotSupportedException");
}
}
private void assertCloneNotSupported(CloneableRef ref) {
try {
ref.clone();
throw new RuntimeException("Reference::clone should throw CloneNotSupportedException");
} catch (CloneNotSupportedException e) {}
}
// override clone to be public that throws CNSE
interface CloneableRef extends Cloneable {
public Object clone() throws CloneNotSupportedException;
}
class SoftRef extends SoftReference<Object> implements CloneableRef {
public SoftRef(Object referent) {
super(referent, QUEUE);
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class WeakRef extends WeakReference<Object> implements CloneableRef {
public WeakRef(Object referent) {
super(referent, QUEUE);
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class PhantomRef extends PhantomReference<Object> implements CloneableRef {
public PhantomRef(Object referent) {
super(referent, QUEUE);
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// override clone to return a new instance
class CloneableReference extends WeakReference<Object> implements Cloneable {
public CloneableReference(Object referent) {
super(referent, QUEUE);
}
public Object clone() throws CloneNotSupportedException {
return new CloneableReference(this.get());
}
}
}

View file

@ -0,0 +1,116 @@
/*
* Copyright (c) 2011, 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
* @bug 4268317 8132306 8175797
* @summary Test if Reference.enqueue() works properly with GC
* @run main ReferenceEnqueue
*/
import java.lang.ref.*;
import java.util.ArrayList;
import java.util.List;
public class ReferenceEnqueue {
public static void main(String args[]) throws Exception {
for (int i=0; i < 5; i++) {
new WeakRef().run();
new ExplicitEnqueue().run();
}
System.out.println("Test passed.");
}
static class WeakRef {
final ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
final Reference<Object> ref;
final int iterations = 1000;
WeakRef() {
this.ref = new WeakReference<Object>(new Object(), queue);
}
void run() throws InterruptedException {
boolean enqueued = false;
System.gc();
for (int i = 0; i < iterations; i++) {
System.gc();
enqueued = (queue.remove(100) == ref);
if (enqueued) break;
}
if (!enqueued) {
// GC have not enqueued refWeak for the timeout period
throw new RuntimeException("Error: reference not enqueued");
}
if (ref.enqueue() == true) {
// enqueue() should return false since
// ref is already enqueued by the GC
throw new RuntimeException("Error: enqueue() returned true;"
+ " expected false");
}
}
}
static class ExplicitEnqueue {
final ReferenceQueue<Object> queue = new ReferenceQueue<>();
final List<Reference<Object>> refs = new ArrayList<>();
final int iterations = 1000;
ExplicitEnqueue() {
this.refs.add(new SoftReference<>(new Object(), queue));
this.refs.add(new WeakReference<>(new Object(), queue));
this.refs.add(new PhantomReference<>(new Object(), queue));
}
void run() throws InterruptedException {
for (Reference<Object> ref : refs) {
if (ref.enqueue() == false) {
throw new RuntimeException("Error: enqueue failed");
}
if (!ref.refersTo(null)) {
throw new RuntimeException("Error: referent must be cleared");
}
}
System.gc();
for (int i = 0; refs.size() > 0 && i < iterations; i++) {
Reference<Object> ref = (Reference<Object>)queue.poll();
if (ref == null) {
System.gc();
Thread.sleep(100);
continue;
}
if (refs.remove(ref) == false) {
throw new RuntimeException("Error: unknown reference " + ref);
}
}
if (!refs.isEmpty()) {
throw new RuntimeException("Error: not all references are removed");
}
}
}
}

View file

@ -0,0 +1,219 @@
/*
* Copyright (c) 2011, 2016, 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 4243978
* @summary Test if Reference.enqueue() works properly with pending references
*/
import java.lang.ref.*;
public class ReferenceEnqueuePending {
static class NumberedWeakReference extends WeakReference<Integer> {
// Add an integer to identify the weak reference object.
int number;
NumberedWeakReference(Integer referent, ReferenceQueue<Integer> q, int i) {
super(referent, q);
number = i;
}
}
static final boolean debug = System.getProperty("test.debug") != null;
static final int iterations = 1000;
static final int gc_trigger = 99;
static int[] a = new int[2 * iterations];
// Keep all weak references alive with the following array.
static NumberedWeakReference[] b = new NumberedWeakReference[iterations];
public static void main(String[] argv) throws Exception {
if (debug) {
System.out.println("Starting the test.");
}
// Raise thread priority to match the referenceHandler
// priority, so that they can race also on a uniprocessor.
raisePriority();
ReferenceQueue<Integer> refQueue = new ReferenceQueue<>();
// Our objective is to let the mutator enqueue
// a Reference object that may already be in the
// pending state because of having been identified
// as weakly reachable at a previous garbage collection.
// To this end, we create many Reference objects, each with a
// a unique integer object as its referant.
// We let the referents become eligible for collection,
// while racing with the garbage collector which may
// have pended some of these Reference objects.
// Finally we check that all of the Reference objects
// end up on the their queue. The test was originally
// submitted to show that such races could break the
// pending list and/or the reference queue, because of sharing
// the same link ("next") for maintaining both lists, thus
// losing some of the Reference objects on either queue.
Integer obj = new Integer(0);
NumberedWeakReference weaky = new NumberedWeakReference(obj, refQueue, 0);
for (int i = 1; i < iterations; i++) {
// Create a new object, dropping the onlY strong reference to
// the previous Integer object.
obj = new Integer(i);
// Trigger gc each gc_trigger iterations.
if ((i % gc_trigger) == 0) {
forceGc(0);
}
// Enqueue every other weaky.
if ((i % 2) == 0) {
weaky.enqueue();
}
// Remember the Reference objects, for testing later.
b[i - 1] = weaky;
// Get a new weaky for the Integer object just
// created, which may be explicitly enqueued in
// our next trip around the loop.
weaky = new NumberedWeakReference(obj, refQueue, i);
}
// Do a final collection to discover and process all
// Reference objects created above, allowing some time
// for the ReferenceHandler thread to queue the References.
forceGc(100);
forceGc(100);
// Verify that all WeakReference objects ended up queued.
checkResult(refQueue, iterations-1);
// Ensure the final weaky is live but won't be enqueued during
// result checking, by ensuring its referent remains live.
// This eliminates behavior changes resulting from different
// compiler optimizations.
Reference.reachabilityFence(weaky);
Reference.reachabilityFence(obj);
System.out.println("Test passed.");
}
private static NumberedWeakReference waitForReference(ReferenceQueue<Integer> queue) {
try {
return (NumberedWeakReference) queue.remove(30000); // 30sec
} catch (InterruptedException ie) {
return null;
}
}
private static void checkResult(ReferenceQueue<Integer> queue,
int expected) {
if (debug) {
System.out.println("Reading the queue");
}
// Empty the queue and record numbers into a[];
NumberedWeakReference weakRead = waitForReference(queue);
int length = 0;
while (weakRead != null) {
a[length++] = weakRead.number;
if (length < expected) {
weakRead = waitForReference(queue);
} else { // Check for unexpected extra entries.
weakRead = (NumberedWeakReference) queue.poll();
}
}
if (debug) {
System.out.println("Reference Queue had " + length + " elements");
}
// verify the queued references: all but the last Reference object
// should have been in the queue.
if (debug) {
System.out.println("Start of final check");
}
// Sort the first "length" elements in array "a[]".
sort(length);
boolean fail = (length != expected);
for (int i = 0; i < length; i++) {
if (a[i] != i) {
if (debug) {
System.out.println("a[" + i + "] is not " + i + " but " + a[i]);
}
fail = true;
}
}
if (fail) {
printMissingElements(length, expected);
throw new RuntimeException("TEST FAILED: only " + length
+ " reference objects have been queued out of "
+ expected);
}
}
private static void printMissingElements(int length, int expected) {
System.out.println("The following numbers were not found in the reference queue: ");
int missing = 0;
int element = 0;
for (int i = 0; i < length; i++) {
while ((a[i] != element) & (element < expected)) {
System.out.print(element + " ");
if (missing % 20 == 19) {
System.out.println(" ");
}
missing++;
element++;
}
element++;
}
System.out.print("\n");
}
private static void forceGc(long millis) throws InterruptedException {
Runtime.getRuntime().gc();
Thread.sleep(millis);
}
// Bubble sort the first "length" elements in array "a".
private static void sort(int length) {
int hold;
if (debug) {
System.out.println("Sorting. Length=" + length);
}
for (int pass = 1; pass < length; pass++) { // passes over the array
for (int i = 0; i < length - pass; i++) { // a single pass
if (a[i] > a[i + 1]) { // then swap
hold = a[i];
a[i] = a[i + 1];
a[i + 1] = hold;
}
} // End of i loop
} // End of pass loop
}
// Raise thread priority so as to increase the
// probability of the mutator succeeding in enqueueing
// an object that is still in the pending state.
// This is (probably) only required for a uniprocessor.
static void raisePriority() {
Thread tr = Thread.currentThread();
tr.setPriority(Thread.MAX_PRIORITY);
}
} // End of class ReferenceEnqueuePending

View file

@ -0,0 +1,80 @@
/*
* 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
* @bug 8188055
* @summary Basic functional test of Reference.refersTo.
*/
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.PhantomReference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
public class ReferenceRefersTo {
private static final void fail(String msg) throws Exception {
throw new RuntimeException(msg);
}
private static final <T extends Reference> void test(T ref,
Object expectedValue,
Object unexpectedValue,
String kind) throws Exception {
if ((expectedValue != null) && ref.refersTo(null)) {
fail(kind + "refers to null");
}
if (!ref.refersTo(expectedValue)) {
fail(kind + " doesn't refer to expected value");
}
if (ref.refersTo(unexpectedValue)) {
fail(kind + " refers to unexpected value");
}
}
public static void main(String[] args) throws Exception {
var queue = new ReferenceQueue<Object>();
var obj0 = new Object();
var obj1 = new Object();
var obj2 = new Object();
var obj3 = new Object();
var pref = new PhantomReference(obj0, queue);
var wref = new WeakReference(obj1);
var sref = new SoftReference(obj2);
test(pref, obj0, obj3, "phantom");
test(wref, obj1, obj3, "weak");
test(sref, obj2, obj3, "soft");
pref.clear();
wref.clear();
sref.clear();
test(pref, null, obj3, "phantom");
test(wref, null, obj3, "weak");
test(sref, null, obj3, "soft");
}
}

View file

@ -0,0 +1,73 @@
/*
* Copyright (c) 1997, 1998, 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 4076283
* @summary java.lang.ref.SoftReference should reliably prevent
* OutOfMemoryErrors
* @author Peter Jones
* @author Mark Reinhold
*/
/* If this test fails, an OutOfMemoryError will be thrown */
import java.lang.ref.SoftReference;
public class Bash {
static class TestReference extends SoftReference {
public static TestReference head;
public TestReference next;
public TestReference(Object referent) {
super(referent);
next = head;
head = this;
}
}
static final int NUM_BLOCKS = 2048;
static final int BLOCK_SIZE = 32768;
public static void main(String[] args) throws Exception {
for (int i = 0; i < NUM_BLOCKS; ++ i) {
TestReference ref = new TestReference(new byte[BLOCK_SIZE]);
}
int emptyCount = 0;
int fullCount = 0;
for (TestReference r = TestReference.head; r != null; r = r.next) {
if (r.get() == null) emptyCount++;
else fullCount++;
}
System.err.println(fullCount + " full, " + emptyCount + " empty ");
}
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 1997, 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 4076287
* @summary Invoking get on a SoftReference shouldn't pin the referent
* @run main/othervm -Xms16m -Xmx16m Pin
*/
import java.lang.ref.SoftReference;
public class Pin {
static final int NUM_BLOCKS = 128;
static final int BLOCK_SIZE = 32768;
public static void main(String[] args) throws Exception {
SoftReference[] blocks = new SoftReference[NUM_BLOCKS];
byte[] block;
System.err.println("Filling array with " + NUM_BLOCKS +
" SoftReferences to blocks of " +
BLOCK_SIZE + " bytes.");
for (int i = 0; i < NUM_BLOCKS; ++ i) {
block = new byte[BLOCK_SIZE];
SoftReference ref = new SoftReference(block);
blocks[i] = ref;
}
block = null;
System.err.println("Allowing SoftReferences to be enqueued.");
System.gc();
Thread.sleep(1000);
/* -- Commenting out the following section will hide the bug -- */
System.err.println("Invoking get() on SoftReferences.");
for (int i = 0; i < NUM_BLOCKS; ++ i) {
block = (byte[]) blocks[i].get();
}
block = null;
/* -- end -- */
System.err.println("Forcing desperate garbage collection...");
java.util.Vector chain = new java.util.Vector();
try {
while (true) {
System.gc();
int[] hungry = new int[65536];
chain.addElement(hungry);
Thread.sleep(100); // yield, for what it's worth
}
} catch (OutOfMemoryError e) {
chain = null; // Free memory for further work.
System.err.println("Got OutOfMemoryError, as expected.");
}
int emptyCount = 0, fullCount = 0;
System.err.print("Examining contents of array:");
for (int i = 0; i < NUM_BLOCKS; ++ i) {
block = (byte[]) blocks[i].get();
if (block == null) {
emptyCount++;
} else {
fullCount++;
}
}
System.err.println(" " + emptyCount + " empty, " +
fullCount + " full.");
if (emptyCount == 0)
throw new Exception("No SoftReference instances were cleared");
}
}