001    /**
002     * Copyright (c) 2000-2013 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            @Override
046            public Thread newThread(Runnable runnable) {
047                    Thread thread = new Thread(
048                            _group, runnable,
049                            _name.concat(StringPool.MINUS).concat(
050                                    String.valueOf(_counter.incrementAndGet())));
051    
052                    thread.setDaemon(true);
053                    thread.setPriority(_priority);
054    
055                    if (_contextClassLoader != null) {
056                            thread.setContextClassLoader(_contextClassLoader);
057                    }
058    
059                    return thread;
060            }
061    
062            private ClassLoader _contextClassLoader;
063            private AtomicInteger _counter = new AtomicInteger();
064            private ThreadGroup _group;
065            private String _name;
066            private int _priority;
067    
068    }