View Javadoc
1   /*
2    * Copyright 2017 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util.internal;
17  
18  import io.netty.util.concurrent.FastThreadLocalThread;
19  
20  import java.lang.ref.ReferenceQueue;
21  import java.lang.ref.WeakReference;
22  import java.security.AccessController;
23  import java.security.PrivilegedAction;
24  import java.util.Set;
25  import java.util.concurrent.atomic.AtomicBoolean;
26  
27  import static io.netty.util.internal.SystemPropertyUtil.getInt;
28  import static java.lang.Math.max;
29  
30  /**
31   * Allows a way to register some {@link Runnable} that will executed once there are no references to an {@link Object}
32   * anymore.
33   *
34   * @deprecated The object cleaner is deprecated for removal.
35   */
36  @Deprecated
37  public final class ObjectCleaner {
38      private static final int REFERENCE_QUEUE_POLL_TIMEOUT_MS =
39              max(500, getInt("io.netty.util.internal.ObjectCleaner.refQueuePollTimeout", 10000));
40  
41      // Package-private for testing
42      static final String CLEANER_THREAD_NAME = ObjectCleaner.class.getSimpleName() + "Thread";
43      // This will hold a reference to the AutomaticCleanerReference which will be removed once we called cleanup()
44      private static final Set<AutomaticCleanerReference> LIVE_SET = new ConcurrentSet<AutomaticCleanerReference>();
45      private static final ReferenceQueue<Object> REFERENCE_QUEUE = new ReferenceQueue<Object>();
46      private static final AtomicBoolean CLEANER_RUNNING = new AtomicBoolean(false);
47      private static final Runnable CLEANER_TASK = new Runnable() {
48          @Override
49          public void run() {
50              boolean interrupted = false;
51              for (;;) {
52                  // Keep on processing as long as the LIVE_SET is not empty and once it becomes empty
53                  // See if we can let this thread complete.
54                  while (!LIVE_SET.isEmpty()) {
55                      final AutomaticCleanerReference reference;
56                      try {
57                          reference = (AutomaticCleanerReference) REFERENCE_QUEUE.remove(REFERENCE_QUEUE_POLL_TIMEOUT_MS);
58                      } catch (InterruptedException ex) {
59                          // Just consume and move on
60                          interrupted = true;
61                          continue;
62                      }
63                      if (reference != null) {
64                          try {
65                              reference.cleanup();
66                          } catch (Throwable ignored) {
67                              // ignore exceptions, and don't log in case the logger throws an exception, blocks, or has
68                              // other unexpected side effects.
69                          }
70                          LIVE_SET.remove(reference);
71                      }
72                  }
73                  CLEANER_RUNNING.set(false);
74  
75                  // Its important to first access the LIVE_SET and then CLEANER_RUNNING to ensure correct
76                  // behavior in multi-threaded environments.
77                  if (LIVE_SET.isEmpty() || !CLEANER_RUNNING.compareAndSet(false, true)) {
78                      // There was nothing added after we set STARTED to false or some other cleanup Thread
79                      // was started already so its safe to let this Thread complete now.
80                      break;
81                  }
82              }
83              if (interrupted) {
84                  // As we caught the InterruptedException above we should mark the Thread as interrupted.
85                  Thread.currentThread().interrupt();
86              }
87          }
88      };
89  
90      /**
91       * Register the given {@link Object} for which the {@link Runnable} will be executed once there are no references
92       * to the object anymore.
93       *
94       * This should only be used if there are no other ways to execute some cleanup once the Object is not reachable
95       * anymore because it is not a cheap way to handle the cleanup.
96       */
97      public static void register(Object object, Runnable cleanupTask) {
98          AutomaticCleanerReference reference = new AutomaticCleanerReference(object,
99                  ObjectUtil.checkNotNull(cleanupTask, "cleanupTask"));
100         // Its important to add the reference to the LIVE_SET before we access CLEANER_RUNNING to ensure correct
101         // behavior in multi-threaded environments.
102         LIVE_SET.add(reference);
103 
104         // Check if there is already a cleaner running.
105         if (CLEANER_RUNNING.compareAndSet(false, true)) {
106             final Thread cleanupThread = new FastThreadLocalThread(CLEANER_TASK);
107             cleanupThread.setPriority(Thread.MIN_PRIORITY);
108             // Set to null to ensure we not create classloader leaks by holding a strong reference to the inherited
109             // classloader.
110             // See:
111             // - https://github.com/netty/netty/issues/7290
112             // - https://bugs.openjdk.java.net/browse/JDK-7008595
113             AccessController.doPrivileged(new PrivilegedAction<Void>() {
114                 @Override
115                 public Void run() {
116                     cleanupThread.setContextClassLoader(null);
117                     return null;
118                 }
119             });
120             cleanupThread.setName(CLEANER_THREAD_NAME);
121 
122             // Mark this as a daemon thread to ensure that we the JVM can exit if this is the only thread that is
123             // running.
124             cleanupThread.setDaemon(true);
125             cleanupThread.start();
126         }
127     }
128 
129     public static int getLiveSetCount() {
130         return LIVE_SET.size();
131     }
132 
133     private ObjectCleaner() {
134         // Only contains a static method.
135     }
136 
137     private static final class AutomaticCleanerReference extends WeakReference<Object> {
138         private final Runnable cleanupTask;
139 
140         AutomaticCleanerReference(Object referent, Runnable cleanupTask) {
141             super(referent, REFERENCE_QUEUE);
142             this.cleanupTask = cleanupTask;
143         }
144 
145         void cleanup() {
146             cleanupTask.run();
147         }
148 
149         @Override
150         public Thread get() {
151             return null;
152         }
153 
154         @Override
155         public void clear() {
156             LIVE_SET.remove(this);
157             super.clear();
158         }
159     }
160 }