--- old/src/java.base/share/classes/java/lang/ref/Cleaner.java 2016-03-24 16:33:10.018496279 +0100 +++ new/src/java.base/share/classes/java/lang/ref/Cleaner.java 2016-03-24 16:33:09.929495812 +0100 @@ -221,6 +221,16 @@ } /** + * Processes next Cleanable that has been waiting in the queue. + * + * @return {@code true} if a Cleanable was found in the queue and + * was processed or {@code false} if the queue was empty. + */ + boolean cleanNextEnqueued() { + return impl.cleanNextEnqueued(); + } + + /** * {@code Cleanable} represents an object and a * cleaning action registered in a {@code Cleaner}. * @since 9 --- old/src/java.base/share/classes/java/lang/ref/Reference.java 2016-03-24 16:33:10.252497507 +0100 +++ new/src/java.base/share/classes/java/lang/ref/Reference.java 2016-03-24 16:33:10.164497045 +0100 @@ -29,7 +29,6 @@ import jdk.internal.HotSpotIntrinsicCandidate; import jdk.internal.misc.JavaLangRefAccess; import jdk.internal.misc.SharedSecrets; -import jdk.internal.ref.Cleaner; /** * Abstract base class for reference objects. This class defines the @@ -107,7 +106,7 @@ * pending: next element in the pending list (or null if last) * otherwise: NULL */ - private transient Reference discovered; /* used by VM */ + private transient Reference discovered; /* used by VM */ /* Object used to synchronize with the garbage collector. The collector @@ -116,7 +115,7 @@ * as possible, allocate no new objects, and avoid calling user code. */ private static class Lock { } - private static Lock lock = new Lock(); + private static final Lock lock = new Lock(); /* List of References waiting to be enqueued. The collector adds @@ -124,7 +123,7 @@ * them. This list is protected by the above lock object. The * list uses the discovered field to link its elements. */ - private static Reference pending = null; + private static Reference pending; /* High-priority thread to enqueue pending References */ @@ -139,11 +138,10 @@ } static { - // pre-load and initialize InterruptedException and Cleaner classes + // pre-load and initialize InterruptedException class // so that we don't get into trouble later in the run loop if there's - // memory shortage while loading/initializing them lazily. + // memory shortage while loading/initializing it lazily. ensureClassInitialized(InterruptedException.class); - ensureClassInitialized(Cleaner.class); } ReferenceHandler(ThreadGroup g, String name) { @@ -152,72 +150,54 @@ public void run() { while (true) { - tryHandlePending(true); + Reference p = getPendingReferences(); + enqueuePendingReferences(p); } } } /** - * Try handle pending {@link Reference} if there is one.

- * Return {@code true} as a hint that there might be another - * {@link Reference} pending or {@code false} when there are no more pending - * {@link Reference}s at the moment and the program can do some other - * useful work instead of looping. - * - * @param waitForNotify if {@code true} and there was no pending - * {@link Reference}, wait until notified from VM - * or interrupted; if {@code false}, return immediately - * when there is no pending {@link Reference}. - * @return {@code true} if there was a {@link Reference} pending and it - * was processed, or we waited for notification and either got it - * or thread was interrupted before being notified; - * {@code false} otherwise. - */ - static boolean tryHandlePending(boolean waitForNotify) { - Reference r; - Cleaner c; - try { - synchronized (lock) { - if (pending != null) { - r = pending; - // 'instanceof' might throw OutOfMemoryError sometimes - // so do this before un-linking 'r' from the 'pending' chain... - c = r instanceof Cleaner ? (Cleaner) r : null; - // unlink 'r' from 'pending' chain - pending = r.discovered; - r.discovered = null; - } else { + * Blocks until GC discovers some pending references and hands them to us. + * + * @return a list of pending references linked via {@link #discovered} field + * with {@code null} marking the end of list. + */ + static Reference getPendingReferences() { + Reference p; + synchronized (lock) { + while ((p = pending) == null) { + try { + lock.wait(); + } catch (OutOfMemoryError x) { // The waiting on the lock may cause an OutOfMemoryError - // because it may try to allocate exception objects. - if (waitForNotify) { - lock.wait(); - } - // retry if waited - return waitForNotify; + // because it may try to allocate InterruptedException object. + // Give other threads CPU time so they hopefully drop some live + // references and GC reclaims some space. + Thread.yield(); + } catch (InterruptedException x) { + // ignore interrupts } } - } catch (OutOfMemoryError x) { - // Give other threads CPU time so they hopefully drop some live references - // and GC reclaims some space. - // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above - // persistently throws OOME for some time... - Thread.yield(); - // retry - return true; - } catch (InterruptedException x) { - // retry - return true; - } - - // Fast path for cleaners - if (c != null) { - c.clean(); - return true; - } - - ReferenceQueue q = r.queue; - if (q != ReferenceQueue.NULL) q.enqueue(r); - return true; + pending = null; + } + return p; + } + + /** + * Enqueue a list of pending {@link Reference}s. + * + * @param p a list of pending references linked via {@link #discovered} + * field with {@code null} marking the end of list + */ + static void enqueuePendingReferences(Reference p) { + while (p != null) { + Reference r = p; + p = r.discovered; + r.discovered = null; + @SuppressWarnings("unchecked") + ReferenceQueue q = (ReferenceQueue) r.queue; + if (q != ReferenceQueue.NULL) q.enqueue(r); + } } static { @@ -235,9 +215,10 @@ // provide access in SharedSecrets SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { + @Override - public boolean tryHandlePendingReference() { - return tryHandlePending(false); + public boolean cleanNextEnqueuedCleanable(Cleaner cleaner) { + return cleaner.cleanNextEnqueued(); } }); } --- old/src/java.base/share/classes/java/nio/Bits.java 2016-03-24 16:33:10.485498730 +0100 +++ new/src/java.base/share/classes/java/nio/Bits.java 2016-03-24 16:33:10.395498258 +0100 @@ -25,13 +25,16 @@ package java.nio; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.StampedLock; import jdk.internal.misc.JavaNioAccess; import jdk.internal.misc.JavaLangRefAccess; import jdk.internal.misc.SharedSecrets; import jdk.internal.misc.Unsafe; import jdk.internal.misc.VM; +import jdk.internal.ref.CleanerFactory; /** * Access to bits, native and otherwise. @@ -597,17 +600,57 @@ // A user-settable upper limit on the maximum amount of allocatable // direct buffer memory. This value may be changed during VM // initialization if it is launched with "-XX:MaxDirectMemorySize=". - private static volatile long maxMemory = VM.maxDirectMemory(); + // A change to maxMemory is published via memoryLimitSet volatile boolean + // flag changing state from false -> true, so maxMemory need not be volatile. + private static long maxMemory = VM.maxDirectMemory(); + private static volatile boolean memoryLimitSet; + private static final AtomicLong reservedMemory = new AtomicLong(); private static final AtomicLong totalCapacity = new AtomicLong(); private static final AtomicLong count = new AtomicLong(); - private static volatile boolean memoryLimitSet; - // max. number of sleeps during try-reserving with exponentially - // increasing delay before throwing OutOfMemoryError: - // 1, 2, 4, 8, 16, 32, 64, 128, 256 (total 511 ms ~ 0.5 s) - // which means that OOME will be thrown after 0.5 s of trying - private static final int MAX_SLEEPS = 9; + // A fair lock for direct memory allocator threads to queue after 1st optimistic + // reservation fails so that only a single thread at a time is retrying + // reservation while: + // - waiting for unreservation events until time out + // - followed by triggering reference discovery + // - followed by another round of waiting for unreservation events until time out + // ... before finally giving up with OutOfMemoryError. + private static final StampedLock reserveLock = new StampedLock(); + + // A counter of unreservations incremented by unreservation threads, + // guarded by unreserveLock, but also read by reservation threads without + // holding unreserveLock, so it must be volatile. + private static volatile int unreserveCount; + + // Last value of 'unreserveCount' observed by reservation threads, + // guarded by reserveLock. If 'lastUnreserveCount' and 'unreserveCount' + // differ, an unreservation event (or multiple events) is detected. + private static int lastUnreserveCount; + + // the System.nanoTime() of the detection of last unreservation event + // by the reservation thread(s), guarded by reserveLock. + private static long lastUnreserveNanoTime; + + // flag indicating if 'lastUnreserveNanoTime' has already been set, + // guarded by reserveLock. + private static boolean lastUnreserveNanoTimeSet; + + // max. wait time for unreservation event before triggering GC and/or + // failing with OOME. + private static final long MAX_UNRESERVE_WAIT_NANOS = + TimeUnit.SECONDS.toNanos(1L); + + // the duration of last successful waiting for unreservation + // event by reservation thread. starts with MAX_UNRESERVE_WAIT_NANOS / 4 + // and is dynamically adjusted at each successful call to awaitUnreserveMemory() + // that actually waited for the event. + private static long lastSuccessfullUnreserveWaitNanos = + MAX_UNRESERVE_WAIT_NANOS / 4; + + // monitor lock via which unreservation threads notify reservation threads + // about the unreservation events. + private static final Object unreserveLock = new Object(); // These methods should be called whenever direct memory is allocated or // freed. They allow the user to control the amount of direct memory @@ -619,57 +662,57 @@ memoryLimitSet = true; } - // optimist! - if (tryReserveMemory(size, cap)) { - return; - } - - final JavaLangRefAccess jlra = SharedSecrets.getJavaLangRefAccess(); + JavaLangRefAccess jlra = SharedSecrets.getJavaLangRefAccess(); - // retry while helping enqueue pending Reference objects - // which includes executing pending Cleaner(s) which includes - // Cleaner(s) that free direct buffer memory - while (jlra.tryHandlePendingReference()) { - if (tryReserveMemory(size, cap)) { - return; - } + // optimist! + long stamp = reserveLock.tryReadLock(); + if (stamp != 0L) try { + // retry reservation while helping the Cleaner thread process enqueued + // Cleanable(s) which includes the ones that free direct buffer memory + // until the queue drains out + do { + if (tryReserveMemory(size, cap)) { + return; + } + } while (jlra.cleanNextEnqueuedCleanable(CleanerFactory.cleaner())); + } finally { + reserveLock.unlockRead(stamp); } - // trigger VM's Reference processing - System.gc(); - - // a retry loop with exponential back-off delays - // (this gives VM some time to do it's job) - boolean interrupted = false; + // reservation threads that don't succeed at first must queue so that + // only one of them at a time is triggering reference discovery and + // retrials with waiting on un-reservation events... + stamp = reserveLock.writeLock(); try { - long sleepTime = 1; - int sleeps = 0; - while (true) { + // retry reservation until there are no unreservation events + // detected for at least 4 times as much as we waited for last + // successful unreservation event but no more than + // MAX_UNRESERVE_WAIT_NANOS. + do { if (tryReserveMemory(size, cap)) { return; } - if (sleeps >= MAX_SLEEPS) { - break; - } - if (!jlra.tryHandlePendingReference()) { - try { - Thread.sleep(sleepTime); - sleepTime <<= 1; - sleeps++; - } catch (InterruptedException e) { - interrupted = true; - } + } while (awaitUnreserveMemory(Math.min(MAX_UNRESERVE_WAIT_NANOS, + lastSuccessfullUnreserveWaitNanos * 4))); + + // trigger reference discovery + System.gc(); + // GC stops the world and can last for a long time, + // so restart timing from 0. + lastUnreserveNanoTime = System.nanoTime(); + + // retry reservation until there are no unreservation events + // detected for at least MAX_UNRESERVE_WAIT_NANOS. + do { + if (tryReserveMemory(size, cap)) { + return; } - } + } while (awaitUnreserveMemory(MAX_UNRESERVE_WAIT_NANOS)); // no luck throw new OutOfMemoryError("Direct buffer memory"); - } finally { - if (interrupted) { - // don't swallow interrupts - Thread.currentThread().interrupt(); - } + reserveLock.unlockWrite(stamp); } } @@ -690,12 +733,69 @@ return false; } + private static boolean awaitUnreserveMemory(long timeoutNanos) { + assert reserveLock.isWriteLocked(); + + // optimistic 1st try without lock + int c; + if ((c = unreserveCount) != lastUnreserveCount) { + lastUnreserveCount = c; + lastUnreserveNanoTime = System.nanoTime(); + lastUnreserveNanoTimeSet = true; + return true; + } + boolean interrupted = false; + try { + synchronized (unreserveLock) { + long nt = System.nanoTime(); + if (!lastUnreserveNanoTimeSet) { + lastUnreserveNanoTime = nt; + lastUnreserveNanoTimeSet = true; + } + long deadline = lastUnreserveNanoTime + timeoutNanos; + long waitUnreserve; + while ((c = unreserveCount) == lastUnreserveCount && + (waitUnreserve = deadline - nt) > 0L) { + interrupted |= waitNanos(unreserveLock, waitUnreserve); + nt = System.nanoTime(); + } + if (c == lastUnreserveCount) { + // time out + return false; + } else { + lastSuccessfullUnreserveWaitNanos = nt - lastUnreserveNanoTime; + lastUnreserveCount = c; + lastUnreserveNanoTime = nt; + return true; + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + private static boolean waitNanos(Object lock, long waitNanos) { + try { + long millis = TimeUnit.NANOSECONDS.toMillis(waitNanos); + int nanos = (int) (waitNanos - TimeUnit.MILLISECONDS.toNanos(millis)); + lock.wait(millis, nanos); + return false; + } catch (InterruptedException e) { + return true; + } + } static void unreserveMemory(long size, int cap) { - long cnt = count.decrementAndGet(); - long reservedMem = reservedMemory.addAndGet(-size); - long totalCap = totalCapacity.addAndGet(-cap); - assert cnt >= 0 && reservedMem >= 0 && totalCap >= 0; + synchronized (unreserveLock) { + long cnt = count.decrementAndGet(); + long reservedMem = reservedMemory.addAndGet(-size); + long totalCap = totalCapacity.addAndGet(-cap); + assert cnt >= 0 && reservedMem >= 0 && totalCap >= 0; + unreserveCount++; + unreserveLock.notifyAll(); + } } // -- Monitoring of direct buffer usage -- --- old/src/java.base/share/classes/java/nio/Direct-X-Buffer.java.template 2016-03-24 16:33:10.761500179 +0100 +++ new/src/java.base/share/classes/java/nio/Direct-X-Buffer.java.template 2016-03-24 16:33:10.666499680 +0100 @@ -30,7 +30,8 @@ import java.io.FileDescriptor; import jdk.internal.misc.Unsafe; import jdk.internal.misc.VM; -import jdk.internal.ref.Cleaner; +import java.lang.ref.Cleaner; +import jdk.internal.ref.CleanerFactory; import sun.nio.ch.DirectBuffer; @@ -98,13 +99,13 @@ } - private final Cleaner cleaner; + private final Cleaner.Cleanable cleaner; - public Cleaner cleaner() { return cleaner; } + public Cleaner.Cleanable cleaner() { return cleaner; } #else[byte] - public Cleaner cleaner() { return null; } + public Cleaner.Cleanable cleaner() { return null; } #end[byte] @@ -136,7 +137,7 @@ } else { address = base; } - cleaner = Cleaner.create(this, new Deallocator(base, size, cap)); + cleaner = CleanerFactory.cleaner().register(this, new Deallocator(base, size, cap)); att = null; #else[rw] super(cap); @@ -176,7 +177,9 @@ #if[rw] super(-1, 0, cap, cap, fd); address = addr; - cleaner = Cleaner.create(this, unmapper); + cleaner = (unmapper == null) + ? null + : CleanerFactory.cleaner().register(this, unmapper); att = null; #else[rw] super(cap, addr, fd, unmapper); --- old/src/java.base/share/classes/jdk/internal/misc/JavaLangRefAccess.java 2016-03-24 16:33:11.020501538 +0100 +++ new/src/java.base/share/classes/jdk/internal/misc/JavaLangRefAccess.java 2016-03-24 16:33:10.923501029 +0100 @@ -25,15 +25,16 @@ package jdk.internal.misc; +import java.lang.ref.Cleaner; + public interface JavaLangRefAccess { /** - * Help ReferenceHandler thread process next pending - * {@link java.lang.ref.Reference} + * Processes next Cleanable that has been waiting in the queue maintained + * by given {@code cleaner}. * - * @return {@code true} if there was a pending reference and it - * was enqueue-ed or {@code false} if there was no - * pending reference + * @return {@code true} if a Cleanable was found in the queue and + * was processed or {@code false} if the queue was empty. */ - boolean tryHandlePendingReference(); + boolean cleanNextEnqueuedCleanable(Cleaner cleaner); } --- old/src/java.base/share/classes/jdk/internal/ref/CleanerImpl.java 2016-03-24 16:33:11.295502981 +0100 +++ new/src/java.base/share/classes/jdk/internal/ref/CleanerImpl.java 2016-03-24 16:33:11.202502493 +0100 @@ -157,6 +157,26 @@ } /** + * Processes next Cleanable that has been waiting in the queue. + * + * @return {@code true} if a Cleanable was found in the queue and + * was processed or {@code false} if the queue was empty. + */ + public boolean cleanNextEnqueued() { + Cleanable ref = (Cleanable) queue.poll(); + if (ref != null) { + try { + ref.clean(); + } catch (Throwable t) { + // ignore exceptions from the cleanup action + } + return true; + } else { + return false; + } + } + + /** * Perform cleaning on an unreachable PhantomReference. */ public static final class PhantomCleanableRef extends PhantomCleanable { --- old/src/java.base/share/classes/sun/nio/ch/DirectBuffer.java 2016-03-24 16:33:11.537504251 +0100 +++ new/src/java.base/share/classes/sun/nio/ch/DirectBuffer.java 2016-03-24 16:33:11.445503768 +0100 @@ -25,8 +25,8 @@ package sun.nio.ch; -import jdk.internal.ref.Cleaner; +import java.lang.ref.Cleaner; public interface DirectBuffer { @@ -34,6 +34,6 @@ public Object attachment(); - public Cleaner cleaner(); + public Cleaner.Cleanable cleaner(); } --- old/src/java.base/share/classes/sun/nio/ch/FileChannelImpl.java 2016-03-24 16:33:11.777505511 +0100 +++ new/src/java.base/share/classes/sun/nio/ch/FileChannelImpl.java 2016-03-24 16:33:11.683505017 +0100 @@ -27,6 +27,7 @@ import java.io.FileDescriptor; import java.io.IOException; +import java.lang.ref.Cleaner; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.ClosedByInterruptException; @@ -47,7 +48,6 @@ import jdk.internal.misc.JavaIOFileDescriptorAccess; import jdk.internal.misc.JavaNioAccess; import jdk.internal.misc.SharedSecrets; -import jdk.internal.ref.Cleaner; import sun.security.action.GetPropertyAction; public class FileChannelImpl @@ -845,7 +845,7 @@ } private static void unmap(MappedByteBuffer bb) { - Cleaner cl = ((DirectBuffer)bb).cleaner(); + Cleaner.Cleanable cl = ((DirectBuffer)bb).cleaner(); if (cl != null) cl.clean(); } --- /dev/null 2016-03-24 08:23:35.340345205 +0100 +++ new/test/java/nio/Buffer/DirectBufferAllocOOMETest.java 2016-03-24 16:33:11.940506366 +0100 @@ -0,0 +1,70 @@ +/* + * Copyright (c) 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. + */ + +import java.lang.ref.Reference; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; + +/** + * @test + * @bug 8149925 + * @summary Test that DirectByteBuffer allocation throws OOME and doesn't block + * indefinitely when MaxDirectMemorySize is exhausted + * + * @run main/othervm -XX:MaxDirectMemorySize=128m DirectBufferAllocOOMETest + */ +public class DirectBufferAllocOOMETest { + static final int CAPACITY = 1024 * 1024; // bytes + static volatile boolean wahr = true; + + static void allocUntilOOME() throws OutOfMemoryError { + List dbbs = new ArrayList<>(); + while (wahr) { + dbbs.add(ByteBuffer.allocateDirect(CAPACITY)); + } + Reference.reachabilityFence(dbbs); + } + + public static void main(String[] args) { + try { + allocUntilOOME(); + throw new IllegalStateException("Unexpected code path"); + } catch (OutOfMemoryError x) { + // expected + } + + // should succeed now + ByteBuffer.allocateDirect(CAPACITY); + + try { + allocUntilOOME(); + throw new IllegalStateException("Unexpected code path"); + } catch (OutOfMemoryError x) { + // expected + } + + // should succeed now + ByteBuffer.allocateDirect(CAPACITY); + } +} --- old/src/java.base/share/classes/jdk/internal/ref/Cleaner.java 2016-03-24 16:33:12.255508019 +0100 +++ /dev/null 2016-03-24 08:23:35.340345205 +0100 @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2003, 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * 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. - */ - -package jdk.internal.ref; - -import java.lang.ref.*; -import java.security.AccessController; -import java.security.PrivilegedAction; - - -/** - * General-purpose phantom-reference-based cleaners. - * - *

Cleaners are a lightweight and more robust alternative to finalization. - * They are lightweight because they are not created by the VM and thus do not - * require a JNI upcall to be created, and because their cleanup code is - * invoked directly by the reference-handler thread rather than by the - * finalizer thread. They are more robust because they use phantom references, - * the weakest type of reference object, thereby avoiding the nasty ordering - * problems inherent to finalization. - * - *

A cleaner tracks a referent object and encapsulates a thunk of arbitrary - * cleanup code. Some time after the GC detects that a cleaner's referent has - * become phantom-reachable, the reference-handler thread will run the cleaner. - * Cleaners may also be invoked directly; they are thread safe and ensure that - * they run their thunks at most once. - * - *

Cleaners are not a replacement for finalization. They should be used - * only when the cleanup code is extremely simple and straightforward. - * Nontrivial cleaners are inadvisable since they risk blocking the - * reference-handler thread and delaying further cleanup and finalization. - * - * - * @author Mark Reinhold - */ - -public class Cleaner - extends PhantomReference - implements Runnable -{ - - // Dummy reference queue, needed because the PhantomReference constructor - // insists that we pass a queue. Nothing will ever be placed on this queue - // since the reference handler invokes cleaners explicitly. - // - private static final ReferenceQueue dummyQueue = new ReferenceQueue<>(); - - // Doubly-linked list of live cleaners, which prevents the cleaners - // themselves from being GC'd before their referents - // - private static Cleaner first = null; - - private Cleaner - next = null, - prev = null; - - private static synchronized Cleaner add(Cleaner cl) { - if (first != null) { - cl.next = first; - first.prev = cl; - } - first = cl; - return cl; - } - - private static synchronized boolean remove(Cleaner cl) { - - // If already removed, do nothing - if (cl.next == cl) - return false; - - // Update list - if (first == cl) { - if (cl.next != null) - first = cl.next; - else - first = cl.prev; - } - if (cl.next != null) - cl.next.prev = cl.prev; - if (cl.prev != null) - cl.prev.next = cl.next; - - // Indicate removal by pointing the cleaner to itself - cl.next = cl; - cl.prev = cl; - return true; - - } - - private final Runnable thunk; - - private Cleaner(Object referent, Runnable thunk) { - super(referent, dummyQueue); - this.thunk = thunk; - } - - /** - * Creates a new cleaner. - * - * @param ob the referent object to be cleaned - * @param thunk - * The cleanup code to be run when the cleaner is invoked. The - * cleanup code is run directly from the reference-handler thread, - * so it should be as simple and straightforward as possible. - * - * @return The new cleaner - */ - public static Cleaner create(Object ob, Runnable thunk) { - if (thunk == null) - return null; - return add(new Cleaner(ob, thunk)); - } - - /** - * Runs this cleaner, if it has not been run before. - */ - public void clean() { - if (!remove(this)) - return; - try { - thunk.run(); - } catch (final Throwable x) { - AccessController.doPrivileged(new PrivilegedAction<>() { - public Void run() { - if (System.err != null) - new Error("Cleaner terminated abnormally", x) - .printStackTrace(); - System.exit(1); - return null; - }}); - } - } - - @Override public void run() { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPackageAccess("jdk.internal.ref"); - this.clean(); - } - -} --- old/test/jdk/internal/ref/Cleaner/ExitOnThrow.java 2016-03-24 16:33:12.426508917 +0100 +++ /dev/null 2016-03-24 08:23:35.340345205 +0100 @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2003, 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. - */ - -/* - * @test - * @bug 4954921 8009259 - * @library /test/lib/share/classes - * @modules java.base/jdk.internal.ref - * @build jdk.test.lib.* - * @build jdk.test.lib.process.* - * @run main ExitOnThrow - * @summary Ensure that if a cleaner throws an exception then the VM exits - */ -import java.util.Arrays; - -import jdk.internal.ref.Cleaner; -import jdk.test.lib.JDKToolLauncher; -import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.process.ProcessTools; - -public class ExitOnThrow { - - static final String cp = System.getProperty("test.classes", "."); - - public static void main(String[] args) throws Exception { - if (args.length == 0) { - String[] cmd = JDKToolLauncher.createUsingTestJDK("java") - .addToolArg("-cp") - .addToolArg(cp) - .addToolArg("ExitOnThrow") - .addToolArg("-executeCleaner") - .getCommand(); - ProcessBuilder pb = new ProcessBuilder(cmd); - OutputAnalyzer out = ProcessTools.executeProcess(pb); - System.out.println("======================"); - System.out.println(Arrays.toString(cmd)); - String msg = " stdout: [" + out.getStdout() + "]\n" + - " stderr: [" + out.getStderr() + "]\n" + - " exitValue = " + out.getExitValue() + "\n"; - System.out.println(msg); - - if (out.getExitValue() != 1) - throw new RuntimeException("Unexpected exit code: " + - out.getExitValue()); - - } else { - Cleaner.create(new Object(), - () -> { throw new RuntimeException("Foo!"); } ); - while (true) { - System.gc(); - Thread.sleep(100); - } - } - } - -}