001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import com.google.common.annotations.GwtIncompatible;
018import com.google.common.annotations.VisibleForTesting;
019import java.io.Closeable;
020import java.io.FileNotFoundException;
021import java.io.IOException;
022import java.lang.ref.PhantomReference;
023import java.lang.ref.Reference;
024import java.lang.ref.ReferenceQueue;
025import java.lang.reflect.Method;
026import java.net.URL;
027import java.net.URLClassLoader;
028import java.util.logging.Level;
029import java.util.logging.Logger;
030import javax.annotation.Nullable;
031
032/**
033 * A reference queue with an associated background thread that dequeues references and invokes
034 * {@link FinalizableReference#finalizeReferent()} on them.
035 *
036 * <p>Keep a strong reference to this object until all of the associated referents have been
037 * finalized. If this object is garbage collected earlier, the backing thread will not invoke {@code
038 * finalizeReferent()} on the remaining references.
039 *
040 * <p>As an example of how this is used, imagine you have a class {@code MyServer} that creates a a
041 * {@link java.net.ServerSocket ServerSocket}, and you would like to ensure that the
042 * {@code ServerSocket} is closed even if the {@code MyServer} object is garbage-collected without
043 * calling its {@code close} method. You <em>could</em> use a finalizer to accomplish this, but that
044 * has a number of well-known problems. Here is how you might use this class instead:
045 *
046 * <pre>   {@code
047 * public class MyServer implements Closeable {
048 *   private static final FinalizableReferenceQueue frq = new FinalizableReferenceQueue();
049 *   // You might also share this between several objects.
050 *
051 *   private static final Set<Reference<?>> references = Sets.newConcurrentHashSet();
052 *   // This ensures that the FinalizablePhantomReference itself is not garbage-collected.
053 *
054 *   private final ServerSocket serverSocket;
055 *
056 *   private MyServer(...) {
057 *     ...
058 *     this.serverSocket = new ServerSocket(...);
059 *     ...
060 *   }
061 *
062 *   public static MyServer create(...) {
063 *     MyServer myServer = new MyServer(...);
064 *     final ServerSocket serverSocket = myServer.serverSocket;
065 *     Reference<?> reference = new FinalizablePhantomReference<MyServer>(myServer, frq) {
066 *       public void finalizeReferent() {
067 *         references.remove(this):
068 *         if (!serverSocket.isClosed()) {
069 *           ...log a message about how nobody called close()...
070 *           try {
071 *             serverSocket.close();
072 *           } catch (IOException e) {
073 *             ...
074 *           }
075 *         }
076 *       }
077 *     };
078 *     references.add(reference);
079 *     return myServer;
080 *   }
081 *
082 *   public void close() {
083 *     serverSocket.close();
084 *   }
085 * }}</pre>
086 *
087 * @author Bob Lee
088 * @since 2.0
089 */
090@GwtIncompatible
091public class FinalizableReferenceQueue implements Closeable {
092  /*
093   * The Finalizer thread keeps a phantom reference to this object. When the client (for example, a
094   * map built by MapMaker) no longer has a strong reference to this object, the garbage collector
095   * will reclaim it and enqueue the phantom reference. The enqueued reference will trigger the
096   * Finalizer to stop.
097   *
098   * If this library is loaded in the system class loader, FinalizableReferenceQueue can load
099   * Finalizer directly with no problems.
100   *
101   * If this library is loaded in an application class loader, it's important that Finalizer not
102   * have a strong reference back to the class loader. Otherwise, you could have a graph like this:
103   *
104   * Finalizer Thread runs instance of -> Finalizer.class loaded by -> Application class loader
105   * which loaded -> ReferenceMap.class which has a static -> FinalizableReferenceQueue instance
106   *
107   * Even if no other references to classes from the application class loader remain, the Finalizer
108   * thread keeps an indirect strong reference to the queue in ReferenceMap, which keeps the
109   * Finalizer running, and as a result, the application class loader can never be reclaimed.
110   *
111   * This means that dynamically loaded web applications and OSGi bundles can't be unloaded.
112   *
113   * If the library is loaded in an application class loader, we try to break the cycle by loading
114   * Finalizer in its own independent class loader:
115   *
116   * System class loader -> Application class loader -> ReferenceMap -> FinalizableReferenceQueue ->
117   * etc. -> Decoupled class loader -> Finalizer
118   *
119   * Now, Finalizer no longer keeps an indirect strong reference to the static
120   * FinalizableReferenceQueue field in ReferenceMap. The application class loader can be reclaimed
121   * at which point the Finalizer thread will stop and its decoupled class loader can also be
122   * reclaimed.
123   *
124   * If any of this fails along the way, we fall back to loading Finalizer directly in the
125   * application class loader.
126   */
127
128  private static final Logger logger = Logger.getLogger(FinalizableReferenceQueue.class.getName());
129
130  private static final String FINALIZER_CLASS_NAME = "com.google.common.base.internal.Finalizer";
131
132  /** Reference to Finalizer.startFinalizer(). */
133  private static final Method startFinalizer;
134
135  static {
136    Class<?> finalizer =
137        loadFinalizer(new SystemLoader(), new DecoupledLoader(), new DirectLoader());
138    startFinalizer = getStartFinalizer(finalizer);
139  }
140
141  /**
142   * The actual reference queue that our background thread will poll.
143   */
144  final ReferenceQueue<Object> queue;
145
146  final PhantomReference<Object> frqRef;
147
148  /**
149   * Whether or not the background thread started successfully.
150   */
151  final boolean threadStarted;
152
153  /**
154   * Constructs a new queue.
155   */
156  public FinalizableReferenceQueue() {
157    // We could start the finalizer lazily, but I'd rather it blow up early.
158    queue = new ReferenceQueue<>();
159    frqRef = new PhantomReference<Object>(this, queue);
160    boolean threadStarted = false;
161    try {
162      startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef);
163      threadStarted = true;
164    } catch (IllegalAccessException impossible) {
165      throw new AssertionError(impossible); // startFinalizer() is public
166    } catch (Throwable t) {
167      logger.log(
168          Level.INFO,
169          "Failed to start reference finalizer thread."
170              + " Reference cleanup will only occur when new references are created.",
171          t);
172    }
173
174    this.threadStarted = threadStarted;
175  }
176
177  @Override
178  public void close() {
179    frqRef.enqueue();
180    cleanUp();
181  }
182
183  /**
184   * Repeatedly dequeues references from the queue and invokes
185   * {@link FinalizableReference#finalizeReferent()} on them until the queue is empty. This method
186   * is a no-op if the background thread was created successfully.
187   */
188  void cleanUp() {
189    if (threadStarted) {
190      return;
191    }
192
193    Reference<?> reference;
194    while ((reference = queue.poll()) != null) {
195      /*
196       * This is for the benefit of phantom references. Weak and soft references will have already
197       * been cleared by this point.
198       */
199      reference.clear();
200      try {
201        ((FinalizableReference) reference).finalizeReferent();
202      } catch (Throwable t) {
203        logger.log(Level.SEVERE, "Error cleaning up after reference.", t);
204      }
205    }
206  }
207
208  /**
209   * Iterates through the given loaders until it finds one that can load Finalizer.
210   *
211   * @return Finalizer.class
212   */
213  private static Class<?> loadFinalizer(FinalizerLoader... loaders) {
214    for (FinalizerLoader loader : loaders) {
215      Class<?> finalizer = loader.loadFinalizer();
216      if (finalizer != null) {
217        return finalizer;
218      }
219    }
220
221    throw new AssertionError();
222  }
223
224  /**
225   * Loads Finalizer.class.
226   */
227  interface FinalizerLoader {
228
229    /**
230     * Returns Finalizer.class or null if this loader shouldn't or can't load it.
231     *
232     * @throws SecurityException if we don't have the appropriate privileges
233     */
234    @Nullable
235    Class<?> loadFinalizer();
236  }
237
238  /**
239   * Tries to load Finalizer from the system class loader. If Finalizer is in the system class path,
240   * we needn't create a separate loader.
241   */
242  static class SystemLoader implements FinalizerLoader {
243    // This is used by the ClassLoader-leak test in FinalizableReferenceQueueTest to disable
244    // finding Finalizer on the system class path even if it is there.
245    @VisibleForTesting static boolean disabled;
246
247    @Nullable
248    @Override
249    public Class<?> loadFinalizer() {
250      if (disabled) {
251        return null;
252      }
253      ClassLoader systemLoader;
254      try {
255        systemLoader = ClassLoader.getSystemClassLoader();
256      } catch (SecurityException e) {
257        logger.info("Not allowed to access system class loader.");
258        return null;
259      }
260      if (systemLoader != null) {
261        try {
262          return systemLoader.loadClass(FINALIZER_CLASS_NAME);
263        } catch (ClassNotFoundException e) {
264          // Ignore. Finalizer is simply in a child class loader.
265          return null;
266        }
267      } else {
268        return null;
269      }
270    }
271  }
272
273  /**
274   * Try to load Finalizer in its own class loader. If Finalizer's thread had a direct reference to
275   * our class loader (which could be that of a dynamically loaded web application or OSGi bundle),
276   * it would prevent our class loader from getting garbage collected.
277   */
278  static class DecoupledLoader implements FinalizerLoader {
279    private static final String LOADING_ERROR =
280        "Could not load Finalizer in its own class loader. Loading Finalizer in the current class "
281            + "loader instead. As a result, you will not be able to garbage collect this class "
282            + "loader. To support reclaiming this class loader, either resolve the underlying "
283            + "issue, or move Guava to your system class path.";
284
285    @Nullable
286    @Override
287    public Class<?> loadFinalizer() {
288      try {
289        /*
290         * We use URLClassLoader because it's the only concrete class loader implementation in the
291         * JDK. If we used our own ClassLoader subclass, Finalizer would indirectly reference this
292         * class loader:
293         *
294         * Finalizer.class -> CustomClassLoader -> CustomClassLoader.class -> This class loader
295         *
296         * System class loader will (and must) be the parent.
297         */
298        ClassLoader finalizerLoader = newLoader(getBaseUrl());
299        return finalizerLoader.loadClass(FINALIZER_CLASS_NAME);
300      } catch (Exception e) {
301        logger.log(Level.WARNING, LOADING_ERROR, e);
302        return null;
303      }
304    }
305
306    /**
307     * Gets URL for base of path containing Finalizer.class.
308     */
309    URL getBaseUrl() throws IOException {
310      // Find URL pointing to Finalizer.class file.
311      String finalizerPath = FINALIZER_CLASS_NAME.replace('.', '/') + ".class";
312      URL finalizerUrl = getClass().getClassLoader().getResource(finalizerPath);
313      if (finalizerUrl == null) {
314        throw new FileNotFoundException(finalizerPath);
315      }
316
317      // Find URL pointing to base of class path.
318      String urlString = finalizerUrl.toString();
319      if (!urlString.endsWith(finalizerPath)) {
320        throw new IOException("Unsupported path style: " + urlString);
321      }
322      urlString = urlString.substring(0, urlString.length() - finalizerPath.length());
323      return new URL(finalizerUrl, urlString);
324    }
325
326    /** Creates a class loader with the given base URL as its classpath. */
327    URLClassLoader newLoader(URL base) {
328      // We use the bootstrap class loader as the parent because Finalizer by design uses
329      // only standard Java classes. That also means that FinalizableReferenceQueueTest
330      // doesn't pick up the wrong version of the Finalizer class.
331      return new URLClassLoader(new URL[] {base}, null);
332    }
333  }
334
335  /**
336   * Loads Finalizer directly using the current class loader. We won't be able to garbage collect
337   * this class loader, but at least the world doesn't end.
338   */
339  static class DirectLoader implements FinalizerLoader {
340    @Override
341    public Class<?> loadFinalizer() {
342      try {
343        return Class.forName(FINALIZER_CLASS_NAME);
344      } catch (ClassNotFoundException e) {
345        throw new AssertionError(e);
346      }
347    }
348  }
349
350  /**
351   * Looks up Finalizer.startFinalizer().
352   */
353  static Method getStartFinalizer(Class<?> finalizer) {
354    try {
355      return finalizer.getMethod(
356          "startFinalizer", Class.class, ReferenceQueue.class, PhantomReference.class);
357    } catch (NoSuchMethodException e) {
358      throw new AssertionError(e);
359    }
360  }
361}