FileCleaningTracker.java

  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. import java.io.File;
  19. import java.lang.ref.PhantomReference;
  20. import java.lang.ref.ReferenceQueue;
  21. import java.nio.file.Path;
  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.  * Keeps track of files awaiting deletion, and deletes them when an associated
  30.  * marker object is reclaimed by the garbage collector.
  31.  * <p>
  32.  * This utility creates a background thread to handle file deletion.
  33.  * Each file to be deleted is registered with a handler object.
  34.  * When the handler object is garbage collected, the file is deleted.
  35.  * </p>
  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.  * </p>
  43.  */
  44. public class FileCleaningTracker {

  45.     // Note: fields are package protected to allow use by test cases

  46.     /**
  47.      * The reaper thread.
  48.      */
  49.     private final class Reaper extends Thread {
  50.         /** Constructs a new Reaper */
  51.         Reaper() {
  52.             super("File Reaper");
  53.             setPriority(MAX_PRIORITY);
  54.             setDaemon(true);
  55.         }

  56.         /**
  57.          * Runs the reaper thread that will delete files as their associated
  58.          * marker objects are reclaimed by the garbage collector.
  59.          */
  60.         @Override
  61.         public void run() {
  62.             // thread exits when exitWhenFinished is true and there are no more tracked objects
  63.             while (!exitWhenFinished || !trackers.isEmpty()) {
  64.                 try {
  65.                     // Wait for a tracker to remove.
  66.                     final Tracker tracker = (Tracker) q.remove(); // cannot return null
  67.                     trackers.remove(tracker);
  68.                     if (!tracker.delete()) {
  69.                         deleteFailures.add(tracker.getPath());
  70.                     }
  71.                     tracker.clear();
  72.                 } catch (final InterruptedException e) {
  73.                     continue;
  74.                 }
  75.             }
  76.         }
  77.     }

  78.     /**
  79.      * Inner class which acts as the reference for a file pending deletion.
  80.      */
  81.     private static final class Tracker extends PhantomReference<Object> {

  82.         /**
  83.          * The full path to the file being tracked.
  84.          */
  85.         private final String path;

  86.         /**
  87.          * The strategy for deleting files.
  88.          */
  89.         private final FileDeleteStrategy deleteStrategy;

  90.         /**
  91.          * Constructs an instance of this class from the supplied parameters.
  92.          *
  93.          * @param path  the full path to the file to be tracked, not null
  94.          * @param deleteStrategy  the strategy to delete the file, null means normal
  95.          * @param marker  the marker object used to track the file, not null
  96.          * @param queue  the queue on to which the tracker will be pushed, not null
  97.          */
  98.         Tracker(final String path, final FileDeleteStrategy deleteStrategy, final Object marker,
  99.                 final ReferenceQueue<? super Object> queue) {
  100.             super(marker, queue);
  101.             this.path = path;
  102.             this.deleteStrategy = deleteStrategy == null ? FileDeleteStrategy.NORMAL : deleteStrategy;
  103.         }

  104.         /**
  105.          * Deletes the file associated with this tracker instance.
  106.          *
  107.          * @return {@code true} if the file was deleted successfully;
  108.          *         {@code false} otherwise.
  109.          */
  110.         public boolean delete() {
  111.             return deleteStrategy.deleteQuietly(new File(path));
  112.         }

  113.         /**
  114.          * Gets the path.
  115.          *
  116.          * @return the path
  117.          */
  118.         public String getPath() {
  119.             return path;
  120.         }
  121.     }

  122.     /**
  123.      * Queue of {@link Tracker} instances being watched.
  124.      */
  125.     ReferenceQueue<Object> q = new ReferenceQueue<>();

  126.     /**
  127.      * Collection of {@link Tracker} instances in existence.
  128.      */
  129.     final Collection<Tracker> trackers = Collections.synchronizedSet(new HashSet<>()); // synchronized

  130.     /**
  131.      * Collection of File paths that failed to delete.
  132.      */
  133.     final List<String> deleteFailures = Collections.synchronizedList(new ArrayList<>());

  134.     /**
  135.      * Whether to terminate the thread when the tracking is complete.
  136.      */
  137.     volatile boolean exitWhenFinished;

  138.     /**
  139.      * The thread that will clean up registered files.
  140.      */
  141.     Thread reaper;

  142.     /**
  143.      * Construct a new instance.
  144.      */
  145.     public FileCleaningTracker() {
  146.         // empty
  147.     }

  148.     /**
  149.      * Adds a tracker to the list of trackers.
  150.      *
  151.      * @param path  the full path to the file to be tracked, not null
  152.      * @param marker  the marker object used to track the file, not null
  153.      * @param deleteStrategy  the strategy to delete the file, null means normal
  154.      */
  155.     private synchronized void addTracker(final String path, final Object marker, final FileDeleteStrategy
  156.             deleteStrategy) {
  157.         // synchronized block protects reaper
  158.         if (exitWhenFinished) {
  159.             throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called");
  160.         }
  161.         if (reaper == null) {
  162.             reaper = new Reaper();
  163.             reaper.start();
  164.         }
  165.         trackers.add(new Tracker(path, deleteStrategy, marker, q));
  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.      * Gets a copy of the file paths that failed to delete.
  200.      *
  201.      * @return a copy of the file paths that failed to delete
  202.      * @since 2.0
  203.      */
  204.     public List<String> getDeleteFailures() {
  205.         return new ArrayList<>(deleteFailures);
  206.     }

  207.     /**
  208.      * Gets the number of files currently being tracked, and therefore
  209.      * awaiting deletion.
  210.      *
  211.      * @return the number of files being tracked
  212.      */
  213.     public int getTrackCount() {
  214.         return trackers.size();
  215.     }

  216.     /**
  217.      * Tracks the specified file, using the provided marker, deleting the file
  218.      * when the marker instance is garbage collected.
  219.      * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
  220.      *
  221.      * @param file  the file to be tracked, not null
  222.      * @param marker  the marker object used to track the file, not null
  223.      * @throws NullPointerException if the file is null
  224.      */
  225.     public void track(final File file, final Object marker) {
  226.         track(file, marker, null);
  227.     }

  228.     /**
  229.      * Tracks the specified file, using the provided marker, deleting the file
  230.      * when the marker instance is garbage collected.
  231.      * The specified deletion strategy is used.
  232.      *
  233.      * @param file  the file to be tracked, not null
  234.      * @param marker  the marker object used to track the file, not null
  235.      * @param deleteStrategy  the strategy to delete the file, null means normal
  236.      * @throws NullPointerException if the file is null
  237.      */
  238.     public void track(final File file, final Object marker, final FileDeleteStrategy deleteStrategy) {
  239.         Objects.requireNonNull(file, "file");
  240.         addTracker(file.getPath(), marker, deleteStrategy);
  241.     }

  242.     /**
  243.      * Tracks the specified file, using the provided marker, deleting the file
  244.      * when the marker instance is garbage collected.
  245.      * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
  246.      *
  247.      * @param file  the file to be tracked, not null
  248.      * @param marker  the marker object used to track the file, not null
  249.      * @throws NullPointerException if the file is null
  250.      * @since 2.14.0
  251.      */
  252.     public void track(final Path file, final Object marker) {
  253.         track(file, marker, null);
  254.     }

  255.     /**
  256.      * Tracks the specified file, using the provided marker, deleting the file
  257.      * when the marker instance is garbage collected.
  258.      * The specified deletion strategy is used.
  259.      *
  260.      * @param file  the file to be tracked, not null
  261.      * @param marker  the marker object used to track the file, not null
  262.      * @param deleteStrategy  the strategy to delete the file, null means normal
  263.      * @throws NullPointerException if the file is null
  264.      * @since 2.14.0
  265.      */
  266.     public void track(final Path file, final Object marker, final FileDeleteStrategy deleteStrategy) {
  267.         Objects.requireNonNull(file, "file");
  268.         addTracker(file.toAbsolutePath().toString(), marker, deleteStrategy);
  269.     }

  270.     /**
  271.      * Tracks the specified file, using the provided marker, deleting the file
  272.      * when the marker instance is garbage collected.
  273.      * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
  274.      *
  275.      * @param path  the full path to the file to be tracked, not null
  276.      * @param marker  the marker object used to track the file, not null
  277.      * @throws NullPointerException if the path is null
  278.      */
  279.     public void track(final String path, final Object marker) {
  280.         track(path, marker, null);
  281.     }

  282.     /**
  283.      * Tracks the specified file, using the provided marker, deleting the file
  284.      * when the marker instance is garbage collected.
  285.      * The specified deletion strategy is used.
  286.      *
  287.      * @param path  the full path to the file to be tracked, not null
  288.      * @param marker  the marker object used to track the file, not null
  289.      * @param deleteStrategy  the strategy to delete the file, null means normal
  290.      * @throws NullPointerException if the path is null
  291.      */
  292.     public void track(final String path, final Object marker, final FileDeleteStrategy deleteStrategy) {
  293.         Objects.requireNonNull(path, "path");
  294.         addTracker(path, marker, deleteStrategy);
  295.     }

  296. }