001/* 002 * (C) Copyright 2010-2015 Nuxeo SA (http://nuxeo.com/) and others. 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 * 016 * Contributors: 017 * Benoit Delbosc 018 * Julien Carsique 019 * 020 */ 021 022package org.nuxeo.launcher.daemon; 023 024import java.util.concurrent.ThreadFactory; 025import java.util.concurrent.atomic.AtomicInteger; 026 027/** 028 * A factory to create daemon thread, this prevents the JVM to hang on exit waiting for non-daemon threads to finish. 029 * 030 * @author ben 031 * @since 5.4.2 032 */ 033public class DaemonThreadFactory implements ThreadFactory { 034 035 private static final AtomicInteger count = new AtomicInteger(0); 036 037 private String basename; 038 039 private boolean isDaemon; 040 041 /** 042 * @param basename String to use in thread name 043 */ 044 public DaemonThreadFactory(String basename) { 045 this(basename, true); 046 } 047 048 /** 049 * @param basename String to use in thread name 050 * @param isDaemon Will created threads be set as daemon ? 051 */ 052 public DaemonThreadFactory(String basename, boolean isDaemon) { 053 this.basename = basename; 054 this.isDaemon = isDaemon; 055 } 056 057 /** 058 * New daemon thread. 059 */ 060 @Override 061 public Thread newThread(final Runnable runnable) { 062 final Thread thread = new Thread(runnable, basename + "-" + count.getAndIncrement()); 063 thread.setDaemon(isDaemon); 064 return thread; 065 } 066 067}