1 /* 2 * Copyright (c) 2015, 2016, 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 jdk.internal.ref; 27 28 import java.lang.ref.Cleaner; 29 import java.lang.ref.Cleaner.Cleanable; 30 import java.lang.ref.ReferenceQueue; 31 import java.security.AccessController; 32 import java.security.PrivilegedAction; 33 import java.util.concurrent.ThreadFactory; 34 import java.util.concurrent.atomic.AtomicInteger; 35 import java.util.function.Function; 36 37 import jdk.internal.misc.InnocuousThread; 38 39 /** 40 * CleanerImpl manages a set of object references and corresponding cleaning actions. 41 * CleanerImpl provides the functionality of {@link java.lang.ref.Cleaner}. 42 */ 43 public final class CleanerImpl implements Runnable { 44 45 /** 46 * An object to access the CleanerImpl from a Cleaner; set by Cleaner init. 47 */ 48 private static Function<Cleaner, CleanerImpl> cleanerImplAccess = null; 49 50 /** 51 * Heads of a CleanableList for each reference type. 52 */ 53 final PhantomCleanable<?> phantomCleanableList; 54 55 final WeakCleanable<?> weakCleanableList; 56 57 final SoftCleanable<?> softCleanableList; 58 59 // The ReferenceQueue of pending cleaning actions 60 final ReferenceQueue<Object> queue; 61 62 /** 63 * Called by Cleaner static initialization to provide the function 64 * to map from Cleaner to CleanerImpl. 65 * @param access a function to map from Cleaner to CleanerImpl 66 */ 67 public static void setCleanerImplAccess(Function<Cleaner, CleanerImpl> access) { 68 if (cleanerImplAccess == null) { 69 cleanerImplAccess = access; 70 } else { 71 throw new InternalError("cleanerImplAccess"); 72 } 73 } 74 75 /** 76 * Called to get the CleanerImpl for a Cleaner. 77 * @param cleaner the cleaner 78 * @return the corresponding CleanerImpl 79 */ 80 static CleanerImpl getCleanerImpl(Cleaner cleaner) { 81 return cleanerImplAccess.apply(cleaner); 82 } 83 84 /** 85 * Constructor for CleanerImpl. 86 */ 87 public CleanerImpl() { 88 queue = new ReferenceQueue<>(); 89 phantomCleanableList = new PhantomCleanableRef(); 90 weakCleanableList = new WeakCleanableRef(); 91 softCleanableList = new SoftCleanableRef(); 92 } 93 94 /** 95 * Starts the Cleaner implementation. 96 * Ensure this is the CleanerImpl for the Cleaner. 97 * When started waits for Cleanables to be queued. 98 * @param cleaner the cleaner 99 * @param threadFactory the thread factory 100 */ 101 public void start(Cleaner cleaner, ThreadFactory threadFactory) { 102 if (getCleanerImpl(cleaner) != this) { 103 throw new AssertionError("wrong cleaner"); 104 } 105 // schedule a nop cleaning action for the cleaner, so the associated thread 106 // will continue to run at least until the cleaner is reclaimable. 107 new CleanerCleanable(cleaner); 108 109 if (threadFactory == null) { 110 threadFactory = CleanerImpl.InnocuousThreadFactory.factory(); 111 } 112 113 // now that there's at least one cleaning action, for the cleaner, 114 // we can start the associated thread, which runs until 115 // all cleaning actions have been run. 116 Thread thread = threadFactory.newThread(this); 117 thread.setDaemon(true); 118 thread.start(); 119 } 120 121 /** 122 * Process queued Cleanables as long as the cleanable lists are not empty. 123 * A Cleanable is in one of the lists for each Object and for the Cleaner 124 * itself. 125 * Terminates when the Cleaner is no longer reachable and 126 * has been cleaned and there are no more Cleanable instances 127 * for which the object is reachable. 128 * <p> 129 * If the thread is a ManagedLocalsThread, the threadlocals 130 * are erased before each cleanup 131 */ 132 @Override 133 public void run() { 134 Thread t = Thread.currentThread(); 135 InnocuousThread mlThread = (t instanceof InnocuousThread) 136 ? (InnocuousThread) t 137 : null; 138 while (!phantomCleanableList.isListEmpty() || 139 !weakCleanableList.isListEmpty() || 140 !softCleanableList.isListEmpty()) { 141 if (mlThread != null) { 142 // Clear the thread locals 143 mlThread.eraseThreadLocals(); 144 } 145 try { 146 // Wait for a Ref, with a timeout to avoid getting hung 147 // due to a race with clear/clean 148 Cleanable ref = (Cleanable) queue.remove(60 * 1000L); 149 if (ref != null) { 150 ref.clean(); 151 } 152 } catch (Throwable e) { 153 // ignore exceptions from the cleanup action 154 // (including interruption of cleanup thread) 155 } 156 } 157 } 158 159 /** 160 * Processes next Cleanable that has been waiting in the queue. 161 * 162 * @return {@code true} if a Cleanable was found in the queue and 163 * was processed or {@code false} if the queue was empty. 164 */ 165 public boolean cleanNextEnqueuedCleanable() { 166 Cleanable ref = (Cleanable) queue.poll(); 167 if (ref != null) { 168 try { 169 ref.clean(); 170 } catch (Throwable t) { 171 // ignore exceptions from the cleanup action 172 } 173 return true; 174 } else { 175 return false; 176 } 177 } 178 179 /** 180 * Perform cleaning on an unreachable PhantomReference. 181 */ 182 public static final class PhantomCleanableRef extends PhantomCleanable<Object> { 183 private final Runnable action; 184 185 /** 186 * Constructor for a phantom cleanable reference. 187 * @param obj the object to monitor 188 * @param cleaner the cleaner 189 * @param action the action Runnable 190 */ 191 public PhantomCleanableRef(Object obj, Cleaner cleaner, Runnable action) { 192 super(obj, cleaner); 193 this.action = action; 194 } 195 196 /** 197 * Constructor used only for root of phantom cleanable list. 198 */ 199 PhantomCleanableRef() { 200 super(); 201 this.action = null; 202 } 203 204 @Override 205 protected void performCleanup() { 206 action.run(); 207 } 208 209 /** 210 * Prevent access to referent even when it is still alive. 211 * 212 * @throws UnsupportedOperationException always 213 */ 214 @Override 215 public Object get() { 216 throw new UnsupportedOperationException("get"); 217 } 218 219 /** 220 * Direct clearing of the referent is not supported. 221 * 222 * @throws UnsupportedOperationException always 223 */ 224 @Override 225 public void clear() { 226 throw new UnsupportedOperationException("clear"); 227 } 228 } 229 230 /** 231 * Perform cleaning on an unreachable WeakReference. 232 */ 233 public static final class WeakCleanableRef extends WeakCleanable<Object> { 234 private final Runnable action; 235 236 /** 237 * Constructor for a weak cleanable reference. 238 * @param obj the object to monitor 239 * @param cleaner the cleaner 240 * @param action the action Runnable 241 */ 242 WeakCleanableRef(Object obj, Cleaner cleaner, Runnable action) { 243 super(obj, cleaner); 244 this.action = action; 245 } 246 247 /** 248 * Constructor used only for root of weak cleanable list. 249 */ 250 WeakCleanableRef() { 251 super(); 252 this.action = null; 253 } 254 255 @Override 256 protected void performCleanup() { 257 action.run(); 258 } 259 260 /** 261 * Prevent access to referent even when it is still alive. 262 * 263 * @throws UnsupportedOperationException always 264 */ 265 @Override 266 public Object get() { 267 throw new UnsupportedOperationException("get"); 268 } 269 270 /** 271 * Direct clearing of the referent is not supported. 272 * 273 * @throws UnsupportedOperationException always 274 */ 275 @Override 276 public void clear() { 277 throw new UnsupportedOperationException("clear"); 278 } 279 } 280 281 /** 282 * Perform cleaning on an unreachable SoftReference. 283 */ 284 public static final class SoftCleanableRef extends SoftCleanable<Object> { 285 private final Runnable action; 286 287 /** 288 * Constructor for a soft cleanable reference. 289 * @param obj the object to monitor 290 * @param cleaner the cleaner 291 * @param action the action Runnable 292 */ 293 SoftCleanableRef(Object obj, Cleaner cleaner, Runnable action) { 294 super(obj, cleaner); 295 this.action = action; 296 } 297 298 /** 299 * Constructor used only for root of soft cleanable list. 300 */ 301 SoftCleanableRef() { 302 super(); 303 this.action = null; 304 } 305 306 @Override 307 protected void performCleanup() { 308 action.run(); 309 } 310 311 /** 312 * Prevent access to referent even when it is still alive. 313 * 314 * @throws UnsupportedOperationException always 315 */ 316 @Override 317 public Object get() { 318 throw new UnsupportedOperationException("get"); 319 } 320 321 /** 322 * Direct clearing of the referent is not supported. 323 * 324 * @throws UnsupportedOperationException always 325 */ 326 @Override 327 public void clear() { 328 throw new UnsupportedOperationException("clear"); 329 } 330 331 } 332 333 /** 334 * A ThreadFactory for InnocuousThreads. 335 * The factory is a singleton. 336 */ 337 static final class InnocuousThreadFactory implements ThreadFactory { 338 final static ThreadFactory factory = new InnocuousThreadFactory(); 339 340 static ThreadFactory factory() { 341 return factory; 342 } 343 344 final AtomicInteger cleanerThreadNumber = new AtomicInteger(); 345 346 public Thread newThread(Runnable r) { 347 return AccessController.doPrivileged(new PrivilegedAction<Thread>() { 348 @Override 349 public Thread run() { 350 Thread t = new InnocuousThread(r); 351 t.setPriority(Thread.MAX_PRIORITY - 2); 352 t.setName("Cleaner-" + cleanerThreadNumber.getAndIncrement()); 353 return t; 354 } 355 }); 356 } 357 } 358 359 /** 360 * A PhantomCleanable implementation for tracking the Cleaner itself. 361 */ 362 static final class CleanerCleanable extends PhantomCleanable<Cleaner> { 363 CleanerCleanable(Cleaner cleaner) { 364 super(cleaner, cleaner); 365 } 366 367 @Override 368 protected void performCleanup() { 369 // no action 370 } 371 } 372 }