1 /*
   2  * Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.misc;
  27 
  28 import java.security.AccessController;
  29 import java.security.PrivilegedAction;
  30 import java.util.SortedSet;
  31 import java.util.TreeSet;
  32 
  33 
  34 /**
  35  * Support for garbage-collection latency requests.
  36  *
  37  * @author   Mark Reinhold
  38  * @since    1.2
  39  */
  40 
  41 public class GC {
  42 
  43     private GC() { }            /* To prevent instantiation */
  44 
  45 
  46     /* Latency-target value indicating that there's no active target
  47      */
  48     private static final long NO_TARGET = Long.MAX_VALUE;
  49 
  50     /* The current latency target, or NO_TARGET if there is no target
  51      */
  52     private static long latencyTarget = NO_TARGET;
  53 
  54     /* The daemon thread that implements the latency-target mechanism,
  55      * or null if there is presently no daemon thread
  56      */
  57     private static Thread daemon = null;
  58 
  59     /* The lock object for the latencyTarget and daemon fields.  The daemon
  60      * thread, if it exists, waits on this lock for notification that the
  61      * latency target has changed.
  62      */
  63     private static class LatencyLock extends Object { };
  64     private static Object lock = new LatencyLock();
  65 
  66 
  67     /**
  68      * Returns the maximum <em>object-inspection age</em>, which is the number
  69      * of real-time milliseconds that have elapsed since the
  70      * least-recently-inspected heap object was last inspected by the garbage
  71      * collector.
  72      *
  73      * <p> For simple stop-the-world collectors this value is just the time
  74      * since the most recent collection.  For generational collectors it is the
  75      * time since the oldest generation was most recently collected.  Other
  76      * collectors are free to return a pessimistic estimate of the elapsed
  77      * time, or simply the time since the last full collection was performed.
  78      *
  79      * <p> Note that in the presence of reference objects, a given object that
  80      * is no longer strongly reachable may have to be inspected multiple times
  81      * before it can be reclaimed.
  82      */
  83     public static native long maxObjectInspectionAge();
  84 
  85     private static class Daemon extends Thread {
  86 
  87         public void run() {
  88             for (;;) {
  89                 long l;
  90                 synchronized (lock) {
  91 
  92                     l = latencyTarget;
  93                     if (l == NO_TARGET) {
  94                         /* No latency target, so exit */
  95                         GC.daemon = null;
  96                         return;
  97                     }
  98 
  99                     long d = maxObjectInspectionAge();
 100                     if (d >= l) {
 101                         /* Do a full collection.  There is a remote possibility
 102                          * that a full collection will occurr between the time
 103                          * we sample the inspection age and the time the GC
 104                          * actually starts, but this is sufficiently unlikely
 105                          * that it doesn't seem worth the more expensive JVM
 106                          * interface that would be required.
 107                          */
 108                         System.gc();
 109                         d = 0;
 110                     }
 111 
 112                     /* Wait for the latency period to expire,
 113                      * or for notification that the period has changed
 114                      */
 115                     try {
 116                         lock.wait(l - d);
 117                     } catch (InterruptedException x) {
 118                         continue;
 119                     }
 120                 }
 121             }
 122         }
 123 
 124         private Daemon(ThreadGroup tg) {
 125             super(tg, null, "GC Daemon", 0L, false);
 126         }
 127 
 128         /* Create a new daemon thread in the root thread group */
 129         public static void create() {
 130             PrivilegedAction<Void> pa = new PrivilegedAction<Void>() {
 131                 public Void run() {
 132                     ThreadGroup tg = Thread.currentThread().getThreadGroup();
 133                     for (ThreadGroup tgn = tg;
 134                          tgn != null;
 135                          tg = tgn, tgn = tg.getParent());
 136                     Daemon d = new Daemon(tg);
 137                     d.setDaemon(true);
 138                     d.setPriority(Thread.MIN_PRIORITY + 1);
 139                     d.start();
 140                     GC.daemon = d;
 141                     return null;
 142                 }};
 143             AccessController.doPrivileged(pa);
 144         }
 145 
 146     }
 147 
 148 
 149     /* Sets the latency target to the given value.
 150      * Must be invoked while holding the lock.
 151      */
 152     private static void setLatencyTarget(long ms) {
 153         latencyTarget = ms;
 154         if (daemon == null) {
 155             /* Create a new daemon thread */
 156             Daemon.create();
 157         } else {
 158             /* Notify the existing daemon thread
 159              * that the lateency target has changed
 160              */
 161             lock.notify();
 162         }
 163     }
 164 
 165 
 166     /**
 167      * Represents an active garbage-collection latency request.  Instances of
 168      * this class are created by the <code>{@link #requestLatency}</code>
 169      * method.  Given a request, the only interesting operation is that of
 170      * cancellation.
 171      */
 172     public static class LatencyRequest
 173         implements Comparable<LatencyRequest> {
 174 
 175         /* Instance counter, used to generate unique identifers */
 176         private static long counter = 0;
 177 
 178         /* Sorted set of active latency requests */
 179         private static SortedSet<LatencyRequest> requests = null;
 180 
 181         /* Examine the request set and reset the latency target if necessary.
 182          * Must be invoked while holding the lock.
 183          */
 184         private static void adjustLatencyIfNeeded() {
 185             if ((requests == null) || requests.isEmpty()) {
 186                 if (latencyTarget != NO_TARGET) {
 187                     setLatencyTarget(NO_TARGET);
 188                 }
 189             } else {
 190                 LatencyRequest r = requests.first();
 191                 if (r.latency != latencyTarget) {
 192                     setLatencyTarget(r.latency);
 193                 }
 194             }
 195         }
 196 
 197         /* The requested latency, or NO_TARGET
 198          * if this request has been cancelled
 199          */
 200         private long latency;
 201 
 202         /* Unique identifier for this request */
 203         private long id;
 204 
 205         private LatencyRequest(long ms) {
 206             if (ms <= 0) {
 207                 throw new IllegalArgumentException("Non-positive latency: "
 208                                                    + ms);
 209             }
 210             this.latency = ms;
 211             synchronized (lock) {
 212                 this.id = ++counter;
 213                 if (requests == null) {
 214                     requests = new TreeSet<LatencyRequest>();
 215                 }
 216                 requests.add(this);
 217                 adjustLatencyIfNeeded();
 218             }
 219         }
 220 
 221         /**
 222          * Cancels this latency request.
 223          *
 224          * @throws  IllegalStateException
 225          *          If this request has already been cancelled
 226          */
 227         public void cancel() {
 228             synchronized (lock) {
 229                 if (this.latency == NO_TARGET) {
 230                     throw new IllegalStateException("Request already"
 231                                                     + " cancelled");
 232                 }
 233                 if (!requests.remove(this)) {
 234                     throw new InternalError("Latency request "
 235                                             + this + " not found");
 236                 }
 237                 if (requests.isEmpty()) requests = null;
 238                 this.latency = NO_TARGET;
 239                 adjustLatencyIfNeeded();
 240             }
 241         }
 242 
 243         public int compareTo(LatencyRequest r) {
 244             long d = this.latency - r.latency;
 245             if (d == 0) d = this.id - r.id;
 246             return (d < 0) ? -1 : ((d > 0) ? +1 : 0);
 247         }
 248 
 249         public String toString() {
 250             return (LatencyRequest.class.getName()
 251                     + "[" + latency + "," + id + "]");
 252         }
 253 
 254     }
 255 
 256 
 257     /**
 258      * Makes a new request for a garbage-collection latency of the given
 259      * number of real-time milliseconds.  A low-priority daemon thread makes a
 260      * best effort to ensure that the maximum object-inspection age never
 261      * exceeds the smallest of the currently active requests.
 262      *
 263      * @param   latency
 264      *          The requested latency
 265      *
 266      * @throws  IllegalArgumentException
 267      *          If the given <code>latency</code> is non-positive
 268      */
 269     public static LatencyRequest requestLatency(long latency) {
 270         return new LatencyRequest(latency);
 271     }
 272 
 273 
 274     /**
 275      * Returns the current smallest garbage-collection latency request, or zero
 276      * if there are no active requests.
 277      */
 278     public static long currentLatencyTarget() {
 279         long t = latencyTarget;
 280         return (t == NO_TARGET) ? 0 : t;
 281     }
 282 
 283 }