001/* 002 * Licensed under the Apache License, Version 2.0 (the "License"); 003 * you may not use this file except in compliance with the License. 004 * You may obtain a copy of the License at 005 * 006 * http://www.apache.org/licenses/LICENSE-2.0 007 * 008 * Unless required by applicable law or agreed to in writing, software 009 * distributed under the License is distributed on an "AS IS" BASIS, 010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 011 * See the License for the specific language governing permissions and 012 * limitations under the License. 013 */ 014package org.gbif.utils.concurrent; 015 016import java.util.concurrent.Executors; 017import java.util.concurrent.ThreadFactory; 018import java.util.concurrent.atomic.AtomicInteger; 019 020/** 021 * Modified Executors DefaultThreadFactory to allow custom named thread pools. 022 * Otherwise, this factory yields the same semantics as the thread factory returned by 023 * {@link Executors#defaultThreadFactory()}. 024 * 025 * Optionally a priority or daemon flag can be provided. 026 */ 027public class NamedThreadFactory implements ThreadFactory { 028 private final ThreadGroup group; 029 private final AtomicInteger threadNumber = new AtomicInteger(1); 030 private final String namePrefix; 031 private final int priority; 032 private final boolean daemon; 033 034 /** 035 * Creates a new named user thread factory using a normal priority. 036 * @param poolName the name prefix of the thread pool which will be appended -number for the individual thread 037 */ 038 public NamedThreadFactory(String poolName) { 039 this(poolName, Thread.NORM_PRIORITY, false); 040 } 041 042 /** 043 * Creates a new named thread factory using explicit priority and daemon settings. 044 */ 045 public NamedThreadFactory(String poolName, int priority, boolean daemon) { 046 SecurityManager s = System.getSecurityManager(); 047 group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); 048 namePrefix = poolName + "-"; 049 this.priority = priority; 050 this.daemon = daemon; 051 } 052 053 @Override 054 public Thread newThread(Runnable r) { 055 Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); 056 t.setPriority(priority); 057 t.setDaemon(daemon); 058 return t; 059 } 060}