1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.apache.commons.io; 18 19 import java.io.File; 20 import java.lang.ref.PhantomReference; 21 import java.lang.ref.ReferenceQueue; 22 import java.util.ArrayList; 23 import java.util.Collection; 24 import java.util.Collections; 25 import java.util.HashSet; 26 import java.util.List; 27 import java.util.Objects; 28 29 /** 30 * Keeps track of files awaiting deletion, and deletes them when an associated 31 * marker object is reclaimed by the garbage collector. 32 * <p> 33 * This utility creates a background thread to handle file deletion. 34 * Each file to be deleted is registered with a handler object. 35 * When the handler object is garbage collected, the file is deleted. 36 * <p> 37 * In an environment with multiple class loaders (a servlet container, for 38 * example), you should consider stopping the background thread if it is no 39 * longer needed. This is done by invoking the method 40 * {@link #exitWhenFinished}, typically in 41 * {@code javax.servlet.ServletContextListener.contextDestroyed(javax.servlet.ServletContextEvent)} or similar. 42 * 43 */ 44 public class FileCleaningTracker { 45 46 // Note: fields are package protected to allow use by test cases 47 48 /** 49 * The reaper thread. 50 */ 51 private final class Reaper extends Thread { 52 /** Constructs a new Reaper */ Reaper()53 Reaper() { 54 super("File Reaper"); 55 setPriority(Thread.MAX_PRIORITY); 56 setDaemon(true); 57 } 58 59 /** 60 * Run the reaper thread that will delete files as their associated 61 * marker objects are reclaimed by the garbage collector. 62 */ 63 @Override run()64 public void run() { 65 // thread exits when exitWhenFinished is true and there are no more tracked objects 66 while (!exitWhenFinished || !trackers.isEmpty()) { 67 try { 68 // Wait for a tracker to remove. 69 final Tracker tracker = (Tracker) q.remove(); // cannot return null 70 trackers.remove(tracker); 71 if (!tracker.delete()) { 72 deleteFailures.add(tracker.getPath()); 73 } 74 tracker.clear(); 75 } catch (final InterruptedException e) { 76 continue; 77 } 78 } 79 } 80 } 81 /** 82 * Inner class which acts as the reference for a file pending deletion. 83 */ 84 private static final class Tracker extends PhantomReference<Object> { 85 86 /** 87 * The full path to the file being tracked. 88 */ 89 private final String path; 90 /** 91 * The strategy for deleting files. 92 */ 93 private final FileDeleteStrategy deleteStrategy; 94 95 /** 96 * Constructs an instance of this class from the supplied parameters. 97 * 98 * @param path the full path to the file to be tracked, not null 99 * @param deleteStrategy the strategy to delete the file, null means normal 100 * @param marker the marker object used to track the file, not null 101 * @param queue the queue on to which the tracker will be pushed, not null 102 */ Tracker(final String path, final FileDeleteStrategy deleteStrategy, final Object marker, final ReferenceQueue<? super Object> queue)103 Tracker(final String path, final FileDeleteStrategy deleteStrategy, final Object marker, 104 final ReferenceQueue<? super Object> queue) { 105 super(marker, queue); 106 this.path = path; 107 this.deleteStrategy = deleteStrategy == null ? FileDeleteStrategy.NORMAL : deleteStrategy; 108 } 109 110 /** 111 * Deletes the file associated with this tracker instance. 112 * 113 * @return {@code true} if the file was deleted successfully; 114 * {@code false} otherwise. 115 */ delete()116 public boolean delete() { 117 return deleteStrategy.deleteQuietly(new File(path)); 118 } 119 120 /** 121 * Return the path. 122 * 123 * @return the path 124 */ getPath()125 public String getPath() { 126 return path; 127 } 128 } 129 /** 130 * Queue of {@link Tracker} instances being watched. 131 */ 132 ReferenceQueue<Object> q = new ReferenceQueue<>(); 133 /** 134 * Collection of {@link Tracker} instances in existence. 135 */ 136 final Collection<Tracker> trackers = Collections.synchronizedSet(new HashSet<>()); // synchronized 137 /** 138 * Collection of File paths that failed to delete. 139 */ 140 final List<String> deleteFailures = Collections.synchronizedList(new ArrayList<>()); 141 142 /** 143 * Whether to terminate the thread when the tracking is complete. 144 */ 145 volatile boolean exitWhenFinished; 146 147 /** 148 * The thread that will clean up registered files. 149 */ 150 Thread reaper; 151 152 /** 153 * Adds a tracker to the list of trackers. 154 * 155 * @param path the full path to the file to be tracked, not null 156 * @param marker the marker object used to track the file, not null 157 * @param deleteStrategy the strategy to delete the file, null means normal 158 */ addTracker(final String path, final Object marker, final FileDeleteStrategy deleteStrategy)159 private synchronized void addTracker(final String path, final Object marker, final FileDeleteStrategy 160 deleteStrategy) { 161 // synchronized block protects reaper 162 if (exitWhenFinished) { 163 throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called"); 164 } 165 if (reaper == null) { 166 reaper = new Reaper(); 167 reaper.start(); 168 } 169 trackers.add(new Tracker(path, deleteStrategy, marker, q)); 170 } 171 172 /** 173 * Call this method to cause the file cleaner thread to terminate when 174 * there are no more objects being tracked for deletion. 175 * <p> 176 * In a simple environment, you don't need this method as the file cleaner 177 * thread will simply exit when the JVM exits. In a more complex environment, 178 * with multiple class loaders (such as an application server), you should be 179 * aware that the file cleaner thread will continue running even if the class 180 * loader it was started from terminates. This can constitute a memory leak. 181 * <p> 182 * For example, suppose that you have developed a web application, which 183 * contains the commons-io jar file in your WEB-INF/lib directory. In other 184 * words, the FileCleaner class is loaded through the class loader of your 185 * web application. If the web application is terminated, but the servlet 186 * container is still running, then the file cleaner thread will still exist, 187 * posing a memory leak. 188 * <p> 189 * This method allows the thread to be terminated. Simply call this method 190 * in the resource cleanup code, such as 191 * {@code javax.servlet.ServletContextListener.contextDestroyed(javax.servlet.ServletContextEvent)}. 192 * Once called, no new objects can be tracked by the file cleaner. 193 */ exitWhenFinished()194 public synchronized void exitWhenFinished() { 195 // synchronized block protects reaper 196 exitWhenFinished = true; 197 if (reaper != null) { 198 synchronized (reaper) { 199 reaper.interrupt(); 200 } 201 } 202 } 203 204 /** 205 * Return the file paths that failed to delete. 206 * 207 * @return the file paths that failed to delete 208 * @since 2.0 209 */ getDeleteFailures()210 public List<String> getDeleteFailures() { 211 return deleteFailures; 212 } 213 214 /** 215 * Retrieve the number of files currently being tracked, and therefore 216 * awaiting deletion. 217 * 218 * @return the number of files being tracked 219 */ getTrackCount()220 public int getTrackCount() { 221 return trackers.size(); 222 } 223 224 /** 225 * Track the specified file, using the provided marker, deleting the file 226 * when the marker instance is garbage collected. 227 * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used. 228 * 229 * @param file the file to be tracked, not null 230 * @param marker the marker object used to track the file, not null 231 * @throws NullPointerException if the file is null 232 */ track(final File file, final Object marker)233 public void track(final File file, final Object marker) { 234 track(file, marker, null); 235 } 236 237 /** 238 * Track the specified file, using the provided marker, deleting the file 239 * when the marker instance is garbage collected. 240 * The specified deletion strategy is used. 241 * 242 * @param file the file to be tracked, not null 243 * @param marker the marker object used to track the file, not null 244 * @param deleteStrategy the strategy to delete the file, null means normal 245 * @throws NullPointerException if the file is null 246 */ track(final File file, final Object marker, final FileDeleteStrategy deleteStrategy)247 public void track(final File file, final Object marker, final FileDeleteStrategy deleteStrategy) { 248 Objects.requireNonNull(file, "file"); 249 addTracker(file.getPath(), marker, deleteStrategy); 250 } 251 252 /** 253 * Track the specified file, using the provided marker, deleting the file 254 * when the marker instance is garbage collected. 255 * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used. 256 * 257 * @param path the full path to the file to be tracked, not null 258 * @param marker the marker object used to track the file, not null 259 * @throws NullPointerException if the path is null 260 */ track(final String path, final Object marker)261 public void track(final String path, final Object marker) { 262 track(path, marker, null); 263 } 264 265 /** 266 * Track the specified file, using the provided marker, deleting the file 267 * when the marker instance is garbage collected. 268 * The specified deletion strategy is used. 269 * 270 * @param path the full path to the file to be tracked, not null 271 * @param marker the marker object used to track the file, not null 272 * @param deleteStrategy the strategy to delete the file, null means normal 273 * @throws NullPointerException if the path is null 274 */ track(final String path, final Object marker, final FileDeleteStrategy deleteStrategy)275 public void track(final String path, final Object marker, final FileDeleteStrategy deleteStrategy) { 276 Objects.requireNonNull(path, "path"); 277 addTracker(path, marker, deleteStrategy); 278 } 279 280 } 281