001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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    }