1 /*
2  * Copyright (c) Facebook, Inc. and its affiliates.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * 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,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.facebook.thrift.server;
18 
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.concurrent.ThreadFactory;
22 import java.util.concurrent.atomic.AtomicInteger;
23 
24 /**
25  * This class is an implementation of the <i>ThreadFactory</i> interface. This is useful to give
26  * Java threads meaningful names which is useful when using a tool like JConsole.
27  */
28 public class TThreadFactoryImpl implements ThreadFactory {
29   protected String id_;
30   protected Long version_;
31   protected ThreadGroup threadGroup_;
32   protected final AtomicInteger threadNbr_ = new AtomicInteger(1);
33   protected static final Map<String, Long> poolVersionByName = new HashMap<String, Long>();
34 
TThreadFactoryImpl(String id)35   public TThreadFactoryImpl(String id) {
36     SecurityManager sm = System.getSecurityManager();
37     threadGroup_ = (sm != null) ? sm.getThreadGroup() : Thread.currentThread().getThreadGroup();
38     Long lastVersion;
39     synchronized (this) {
40       if ((lastVersion = poolVersionByName.get(id)) == null) {
41         lastVersion = Long.valueOf(-1);
42       }
43       poolVersionByName.put(id, lastVersion + 1);
44     }
45     version_ = lastVersion != null ? lastVersion + 1 : 0;
46     id_ = id;
47   }
48 
newThread(Runnable runnable)49   public Thread newThread(Runnable runnable) {
50     String name = id_ + "-" + version_ + "-thread-" + threadNbr_.getAndIncrement();
51     Thread thread = new Thread(threadGroup_, runnable, name);
52     return thread;
53   }
54 }
55