1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.tomcat.util.threads;
18
19 import java.security.AccessController;
20 import java.security.PrivilegedAction;
21 import java.util.concurrent.ThreadFactory;
22 import java.util.concurrent.atomic.AtomicInteger;
23
24 import org.apache.tomcat.util.security.PrivilegedSetTccl;
25
26 /**
27  * Simple task thread factory to use to create threads for an executor
28  * implementation.
29  */

30 public class TaskThreadFactory implements ThreadFactory {
31
32     private final ThreadGroup group;
33     private final AtomicInteger threadNumber = new AtomicInteger(1);
34     private final String namePrefix;
35     private final boolean daemon;
36     private final int threadPriority;
37
38     public TaskThreadFactory(String namePrefix, boolean daemon, int priority) {
39         SecurityManager s = System.getSecurityManager();
40         group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
41         this.namePrefix = namePrefix;
42         this.daemon = daemon;
43         this.threadPriority = priority;
44     }
45
46     @Override
47     public Thread newThread(Runnable r) {
48         TaskThread t = new TaskThread(group, r, namePrefix + threadNumber.getAndIncrement());
49         t.setDaemon(daemon);
50         t.setPriority(threadPriority);
51
52         // Set the context class loader of newly created threads to be the class
53         // loader that loaded this factory. This avoids retaining references to
54         // web application class loaders and similar.
55         if (Constants.IS_SECURITY_ENABLED) {
56             PrivilegedAction<Void> pa = new PrivilegedSetTccl(
57                     t, getClass().getClassLoader());
58             AccessController.doPrivileged(pa);
59         } else {
60             t.setContextClassLoader(getClass().getClassLoader());
61         }
62
63         return t;
64     }
65 }
66