001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.util;
016    
017    import java.util.concurrent.ThreadFactory;
018    import java.util.concurrent.atomic.AtomicInteger;
019    
020    /**
021     * @author Michael C. Han
022     * @author Shuyang Zhou
023     */
024    public class NamedThreadFactory implements ThreadFactory {
025    
026            public NamedThreadFactory(
027                    String name, int priority, ClassLoader contextClassLoader) {
028    
029                    SecurityManager securityManager = System.getSecurityManager();
030    
031                    if (securityManager != null) {
032                            _group = securityManager.getThreadGroup();
033                    }
034                    else {
035                            Thread currentThread = Thread.currentThread();
036    
037                            _group = currentThread.getThreadGroup();
038                    }
039    
040                    _name = name;
041                    _priority = priority;
042                    _contextClassLoader = contextClassLoader;
043            }
044    
045            public Thread newThread(Runnable runnable) {
046                    Thread thread = new Thread(
047                            _group, runnable,
048                            _name.concat(StringPool.MINUS).concat(
049                                    String.valueOf(_counter.incrementAndGet())));
050    
051                    thread.setDaemon(true);
052                    thread.setPriority(_priority);
053    
054                    if (_contextClassLoader != null) {
055                            thread.setContextClassLoader(_contextClassLoader);
056                    }
057    
058                    return thread;
059            }
060    
061            private ClassLoader _contextClassLoader;
062            private AtomicInteger _counter = new AtomicInteger();
063            private ThreadGroup _group;
064            private String _name;
065            private int _priority;
066    
067    }