001/*
002 * (C) Copyright 2010-2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Benoit Delbosc
016 *     Julien Carsique
017 *
018 */
019
020package org.nuxeo.launcher.daemon;
021
022import java.util.concurrent.ThreadFactory;
023import java.util.concurrent.atomic.AtomicInteger;
024
025/**
026 * A factory to create daemon thread, this prevents the JVM to hang on exit waiting for non-daemon threads to finish.
027 *
028 * @author ben
029 * @since 5.4.2
030 */
031public class DaemonThreadFactory implements ThreadFactory {
032
033    private static final AtomicInteger count = new AtomicInteger(0);
034
035    private String basename;
036
037    private boolean isDaemon;
038
039    /**
040     * @param basename String to use in thread name
041     */
042    public DaemonThreadFactory(String basename) {
043        this(basename, true);
044    }
045
046    /**
047     * @param basename String to use in thread name
048     * @param isDaemon Will created threads be set as daemon ?
049     */
050    public DaemonThreadFactory(String basename, boolean isDaemon) {
051        this.basename = basename;
052        this.isDaemon = isDaemon;
053    }
054
055    /**
056     * New daemon thread.
057     */
058    @Override
059    public Thread newThread(final Runnable runnable) {
060        final Thread thread = new Thread(runnable, basename + "-" + count.getAndIncrement());
061        thread.setDaemon(isDaemon);
062        return thread;
063    }
064
065}