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