001package org.gbif.utils.concurrent;
002
003import java.util.concurrent.Executors;
004import java.util.concurrent.ThreadFactory;
005import java.util.concurrent.atomic.AtomicInteger;
006
007/**
008 * Modified Executors DefaultThreadFactory to allow custom named thread pools.
009 * Otherwise, this factory yields the same semantics as the thread factory returned by
010 * {@link Executors#defaultThreadFactory()}.
011 *
012 * Optionally a priority or daemon flag can be provided.
013 */
014public class NamedThreadFactory implements ThreadFactory {
015  private final ThreadGroup group;
016  private final AtomicInteger threadNumber = new AtomicInteger(1);
017  private final String namePrefix;
018  private final int priority;
019  private final boolean daemon;
020
021
022  /**
023   * Creates a new named user thread factory using a normal priority.
024   * @param poolName the name prefix of the thread pool which will be appended -number for the individual thread
025   */
026  public NamedThreadFactory(String poolName) {
027    this(poolName, Thread.NORM_PRIORITY, false);
028  }
029
030  /**
031   * Creates a new named thread factory using explicit priority and daemon settings.
032   */
033  public NamedThreadFactory(String poolName, int priority, boolean daemon) {
034    SecurityManager s = System.getSecurityManager();
035    group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
036    namePrefix = poolName + "-";
037    this.priority = priority;
038    this.daemon = daemon;
039  }
040
041  public Thread newThread(Runnable r) {
042    Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
043    t.setPriority(priority);
044    t.setDaemon(daemon);
045    return t;
046  }
047}