001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.io; 018 019import java.io.File; 020import java.lang.ref.PhantomReference; 021import java.lang.ref.ReferenceQueue; 022import java.util.ArrayList; 023import java.util.Collection; 024import java.util.Collections; 025import java.util.HashSet; 026import java.util.List; 027import java.util.Objects; 028 029/** 030 * Keeps track of files awaiting deletion, and deletes them when an associated 031 * marker object is reclaimed by the garbage collector. 032 * <p> 033 * This utility creates a background thread to handle file deletion. 034 * Each file to be deleted is registered with a handler object. 035 * When the handler object is garbage collected, the file is deleted. 036 * <p> 037 * In an environment with multiple class loaders (a servlet container, for 038 * example), you should consider stopping the background thread if it is no 039 * longer needed. This is done by invoking the method 040 * {@link #exitWhenFinished}, typically in 041 * {@code javax.servlet.ServletContextListener.contextDestroyed(javax.servlet.ServletContextEvent)} or similar. 042 * 043 */ 044public class FileCleaningTracker { 045 046 // Note: fields are package protected to allow use by test cases 047 048 /** 049 * Queue of <code>Tracker</code> instances being watched. 050 */ 051 ReferenceQueue<Object> q = new ReferenceQueue<>(); 052 /** 053 * Collection of <code>Tracker</code> instances in existence. 054 */ 055 final Collection<Tracker> trackers = Collections.synchronizedSet(new HashSet<Tracker>()); // synchronized 056 /** 057 * Collection of File paths that failed to delete. 058 */ 059 final List<String> deleteFailures = Collections.synchronizedList(new ArrayList<String>()); 060 /** 061 * Whether to terminate the thread when the tracking is complete. 062 */ 063 volatile boolean exitWhenFinished = false; 064 /** 065 * The thread that will clean up registered files. 066 */ 067 Thread reaper; 068 069 //----------------------------------------------------------------------- 070 /** 071 * Track the specified file, using the provided marker, deleting the file 072 * when the marker instance is garbage collected. 073 * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used. 074 * 075 * @param file the file to be tracked, not null 076 * @param marker the marker object used to track the file, not null 077 * @throws NullPointerException if the file is null 078 */ 079 public void track(final File file, final Object marker) { 080 track(file, marker, null); 081 } 082 083 /** 084 * Track the specified file, using the provided marker, deleting the file 085 * when the marker instance is garbage collected. 086 * The specified deletion strategy is used. 087 * 088 * @param file the file to be tracked, not null 089 * @param marker the marker object used to track the file, not null 090 * @param deleteStrategy the strategy to delete the file, null means normal 091 * @throws NullPointerException if the file is null 092 */ 093 public void track(final File file, final Object marker, final FileDeleteStrategy deleteStrategy) { 094 Objects.requireNonNull(file, "file"); 095 addTracker(file.getPath(), marker, deleteStrategy); 096 } 097 098 /** 099 * Track the specified file, using the provided marker, deleting the file 100 * when the marker instance is garbage collected. 101 * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used. 102 * 103 * @param path the full path to the file to be tracked, not null 104 * @param marker the marker object used to track the file, not null 105 * @throws NullPointerException if the path is null 106 */ 107 public void track(final String path, final Object marker) { 108 track(path, marker, null); 109 } 110 111 /** 112 * Track the specified file, using the provided marker, deleting the file 113 * when the marker instance is garbage collected. 114 * The specified deletion strategy is used. 115 * 116 * @param path the full path to the file to be tracked, not null 117 * @param marker the marker object used to track the file, not null 118 * @param deleteStrategy the strategy to delete the file, null means normal 119 * @throws NullPointerException if the path is null 120 */ 121 public void track(final String path, final Object marker, final FileDeleteStrategy deleteStrategy) { 122 Objects.requireNonNull(path, "path"); 123 addTracker(path, marker, deleteStrategy); 124 } 125 126 /** 127 * Adds a tracker to the list of trackers. 128 * 129 * @param path the full path to the file to be tracked, not null 130 * @param marker the marker object used to track the file, not null 131 * @param deleteStrategy the strategy to delete the file, null means normal 132 */ 133 private synchronized void addTracker(final String path, final Object marker, final FileDeleteStrategy 134 deleteStrategy) { 135 // synchronized block protects reaper 136 if (exitWhenFinished) { 137 throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called"); 138 } 139 if (reaper == null) { 140 reaper = new Reaper(); 141 reaper.start(); 142 } 143 trackers.add(new Tracker(path, deleteStrategy, marker, q)); 144 } 145 146 //----------------------------------------------------------------------- 147 /** 148 * Retrieve the number of files currently being tracked, and therefore 149 * awaiting deletion. 150 * 151 * @return the number of files being tracked 152 */ 153 public int getTrackCount() { 154 return trackers.size(); 155 } 156 157 /** 158 * Return the file paths that failed to delete. 159 * 160 * @return the file paths that failed to delete 161 * @since 2.0 162 */ 163 public List<String> getDeleteFailures() { 164 return deleteFailures; 165 } 166 167 /** 168 * Call this method to cause the file cleaner thread to terminate when 169 * there are no more objects being tracked for deletion. 170 * <p> 171 * In a simple environment, you don't need this method as the file cleaner 172 * thread will simply exit when the JVM exits. In a more complex environment, 173 * with multiple class loaders (such as an application server), you should be 174 * aware that the file cleaner thread will continue running even if the class 175 * loader it was started from terminates. This can constitute a memory leak. 176 * <p> 177 * For example, suppose that you have developed a web application, which 178 * contains the commons-io jar file in your WEB-INF/lib directory. In other 179 * words, the FileCleaner class is loaded through the class loader of your 180 * web application. If the web application is terminated, but the servlet 181 * container is still running, then the file cleaner thread will still exist, 182 * posing a memory leak. 183 * <p> 184 * This method allows the thread to be terminated. Simply call this method 185 * in the resource cleanup code, such as 186 * {@code javax.servlet.ServletContextListener.contextDestroyed(javax.servlet.ServletContextEvent)}. 187 * Once called, no new objects can be tracked by the file cleaner. 188 */ 189 public synchronized void exitWhenFinished() { 190 // synchronized block protects reaper 191 exitWhenFinished = true; 192 if (reaper != null) { 193 synchronized (reaper) { 194 reaper.interrupt(); 195 } 196 } 197 } 198 199 //----------------------------------------------------------------------- 200 /** 201 * The reaper thread. 202 */ 203 private final class Reaper extends Thread { 204 /** Construct a new Reaper */ 205 Reaper() { 206 super("File Reaper"); 207 setPriority(Thread.MAX_PRIORITY); 208 setDaemon(true); 209 } 210 211 /** 212 * Run the reaper thread that will delete files as their associated 213 * marker objects are reclaimed by the garbage collector. 214 */ 215 @Override 216 public void run() { 217 // thread exits when exitWhenFinished is true and there are no more tracked objects 218 while (exitWhenFinished == false || trackers.size() > 0) { 219 try { 220 // Wait for a tracker to remove. 221 final Tracker tracker = (Tracker) q.remove(); // cannot return null 222 trackers.remove(tracker); 223 if (!tracker.delete()) { 224 deleteFailures.add(tracker.getPath()); 225 } 226 tracker.clear(); 227 } catch (final InterruptedException e) { 228 continue; 229 } 230 } 231 } 232 } 233 234 //----------------------------------------------------------------------- 235 /** 236 * Inner class which acts as the reference for a file pending deletion. 237 */ 238 private static final class Tracker extends PhantomReference<Object> { 239 240 /** 241 * The full path to the file being tracked. 242 */ 243 private final String path; 244 /** 245 * The strategy for deleting files. 246 */ 247 private final FileDeleteStrategy deleteStrategy; 248 249 /** 250 * Constructs an instance of this class from the supplied parameters. 251 * 252 * @param path the full path to the file to be tracked, not null 253 * @param deleteStrategy the strategy to delete the file, null means normal 254 * @param marker the marker object used to track the file, not null 255 * @param queue the queue on to which the tracker will be pushed, not null 256 */ 257 Tracker(final String path, final FileDeleteStrategy deleteStrategy, final Object marker, 258 final ReferenceQueue<? super Object> queue) { 259 super(marker, queue); 260 this.path = path; 261 this.deleteStrategy = deleteStrategy == null ? FileDeleteStrategy.NORMAL : deleteStrategy; 262 } 263 264 /** 265 * Return the path. 266 * 267 * @return the path 268 */ 269 public String getPath() { 270 return path; 271 } 272 273 /** 274 * Deletes the file associated with this tracker instance. 275 * 276 * @return {@code true} if the file was deleted successfully; 277 * {@code false} otherwise. 278 */ 279 public boolean delete() { 280 return deleteStrategy.deleteQuietly(new File(path)); 281 } 282 } 283 284}