InnocuousThread.java 6.8 KB
Newer Older
1 2 3 4 5
/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
C
chegar 已提交
6
 * under the terms of the GNU General Public License version 2 only, as
7 8 9 10
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
C
chegar 已提交
11
 * This code is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
C
chegar 已提交
13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 15 16
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
C
chegar 已提交
17
 * You should have received a copy of the GNU General Public License version
18
 * 2 along with this work; if not, write to the Free Software Foundation,
C
chegar 已提交
19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
 *
C
chegar 已提交
21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 23 24 25
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

26
package jdk.internal.misc;
27 28

import java.security.AccessControlContext;
29
import java.security.AccessController;
30
import java.security.ProtectionDomain;
31 32
import java.security.PrivilegedAction;
import java.util.concurrent.atomic.AtomicInteger;
33 34 35 36 37

/**
 * A thread that has no permissions, is not a member of any user-defined
 * ThreadGroup and supports the ability to erase ThreadLocals.
 */
38
public final class InnocuousThread extends Thread {
39
    private static final jdk.internal.misc.Unsafe UNSAFE;
40 41
    private static final long THREAD_LOCALS;
    private static final long INHERITABLE_THREAD_LOCALS;
42
    private static final ThreadGroup INNOCUOUSTHREADGROUP;
43 44
    private static final AccessControlContext ACC;
    private static final long INHERITEDACCESSCONTROLCONTEXT;
45
    private static final long CONTEXTCLASSLOADER;
46

47
    private static final AtomicInteger threadNumber = new AtomicInteger(1);
48 49 50
    private static String newName() {
        return "InnocuousThread-" + threadNumber.getAndIncrement();
    }
51

52 53 54 55 56 57 58 59 60 61 62 63 64
    /**
     * Returns a new InnocuousThread with an auto-generated thread name
     * and its context class loader is set to the system class loader.
     */
    public static Thread newThread(Runnable target) {
        return newThread(newName(), target);
    }

    /**
     * Returns a new InnocuousThread with its context class loader
     * set to the system class loader.
     */
    public static Thread newThread(String name, Runnable target) {
65 66 67 68 69 70 71 72 73 74
        return AccessController.doPrivileged(
                new PrivilegedAction<Thread>() {
                    @Override
                    public Thread run() {
                        return new InnocuousThread(INNOCUOUSTHREADGROUP,
                                                   target,
                                                   name,
                                                   ClassLoader.getSystemClassLoader());
                    }
                });
75 76
    }

77 78 79 80 81 82 83 84 85 86 87 88
    /**
     * Returns a new InnocuousThread with an auto-generated thread name.
     * Its context class loader is set to null.
     */
    public static Thread newSystemThread(Runnable target) {
        return newSystemThread(newName(), target);
    }

    /**
     * Returns a new InnocuousThread with null context class loader.
     */
    public static Thread newSystemThread(String name, Runnable target) {
89 90 91 92 93 94 95 96
        return AccessController.doPrivileged(
                new PrivilegedAction<Thread>() {
                    @Override
                    public Thread run() {
                        return new InnocuousThread(INNOCUOUSTHREADGROUP,
                                                   target, name, null);
                    }
                });
97 98
    }

99
    private InnocuousThread(ThreadGroup group, Runnable target, String name, ClassLoader tccl) {
100
        super(group, target, name, 0L, false);
101
        UNSAFE.putObjectRelease(this, INHERITEDACCESSCONTROLCONTEXT, ACC);
A
Merge  
amurillo 已提交
102
        UNSAFE.putObjectRelease(this, CONTEXTCLASSLOADER, tccl);
103 104 105 106 107 108 109 110 111
    }

    @Override
    public void setUncaughtExceptionHandler(UncaughtExceptionHandler x) {
        // silently fail
    }

    @Override
    public void setContextClassLoader(ClassLoader cl) {
112
        // Allow clearing of the TCCL to remove the reference to the system classloader.
113
        if (cl == null)
114
            super.setContextClassLoader(null);
115 116
        else
            throw new SecurityException("setContextClassLoader");
117 118
    }

119 120 121 122 123 124 125 126
    /**
     * Drops all thread locals (and inherited thread locals).
     */
    public final void eraseThreadLocals() {
        UNSAFE.putObject(this, THREAD_LOCALS, null);
        UNSAFE.putObject(this, INHERITABLE_THREAD_LOCALS, null);
    }

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    // ensure run method is run only once
    private volatile boolean hasRun;

    @Override
    public void run() {
        if (Thread.currentThread() == this && !hasRun) {
            hasRun = true;
            super.run();
        }
    }

    // Use Unsafe to access Thread group and ThreadGroup parent fields
    static {
        try {
            ACC = new AccessControlContext(new ProtectionDomain[] {
                new ProtectionDomain(null, null)
            });

            // Find and use topmost ThreadGroup as parent of new group
146
            UNSAFE = jdk.internal.misc.Unsafe.getUnsafe();
147 148 149
            Class<?> tk = Thread.class;
            Class<?> gk = ThreadGroup.class;

150
            THREAD_LOCALS = UNSAFE.objectFieldOffset(tk, "threadLocals");
151
            INHERITABLE_THREAD_LOCALS = UNSAFE.objectFieldOffset
152
                    (tk, "inheritableThreadLocals");
153
            INHERITEDACCESSCONTROLCONTEXT = UNSAFE.objectFieldOffset
154
                (tk, "inheritedAccessControlContext");
155
            CONTEXTCLASSLOADER = UNSAFE.objectFieldOffset
156
                (tk, "contextClassLoader");
157

158 159
            long tg = UNSAFE.objectFieldOffset(tk, "group");
            long gp = UNSAFE.objectFieldOffset(gk, "parent");
160 161 162 163 164 165 166 167 168
            ThreadGroup group = (ThreadGroup)
                UNSAFE.getObject(Thread.currentThread(), tg);

            while (group != null) {
                ThreadGroup parent = (ThreadGroup)UNSAFE.getObject(group, gp);
                if (parent == null)
                    break;
                group = parent;
            }
169 170
            final ThreadGroup root = group;
            INNOCUOUSTHREADGROUP = AccessController.doPrivileged(
171 172 173 174 175 176
                new PrivilegedAction<ThreadGroup>() {
                    @Override
                    public ThreadGroup run() {
                        return new ThreadGroup(root, "InnocuousThreadGroup");
                    }
                });
177 178 179 180 181
        } catch (Exception e) {
            throw new Error(e);
        }
    }
}