001package io.ebeaninternal.server.lib; 002 003 004import java.util.concurrent.ThreadFactory; 005import java.util.concurrent.atomic.AtomicInteger; 006 007/** 008 * ThreadFactory for Daemon threads. 009 * <p> 010 * Daemon threads do not stop a JVM stopping. If an application only has Daemon 011 * threads left it will shutdown. 012 * </p> 013 * <p> 014 * In using Daemon threads you need to either not care about being interrupted 015 * on shutdown or register with the JVM shutdown hook to perform a nice shutdown 016 * of the daemon threads etc. 017 * </p> 018 * 019 * @author rbygrave 020 */ 021public class DaemonThreadFactory implements ThreadFactory { 022 023 private static final AtomicInteger poolNumber = new AtomicInteger(1); 024 025 private final ThreadGroup group; 026 027 private final AtomicInteger threadNumber = new AtomicInteger(1); 028 029 private final String namePrefix; 030 031 public DaemonThreadFactory(String namePrefix) { 032 SecurityManager s = System.getSecurityManager(); 033 this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); 034 this.namePrefix = namePrefix != null ? namePrefix : "pool-" + poolNumber.getAndIncrement() + "-thread-"; 035 } 036 037 @Override 038 public Thread newThread(Runnable r) { 039 040 Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); 041 042 t.setDaemon(true); 043 044 if (t.getPriority() != Thread.NORM_PRIORITY) { 045 t.setPriority(Thread.NORM_PRIORITY); 046 } 047 048 return t; 049 } 050}