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