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