View Javadoc

1   /*
2    * This file is part of AceLogger.
3    * 
4    * AceLogger is free software: you can redistribute it and/or modify it under the terms of the GNU
5    * Lesser General Public License as published by the Free Software Foundation, either version 3 of
6    * the License, or (at your option) any later version.
7    * 
8    * AceLogger is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
9    * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10   * Lesser General Public License for more details.
11   * 
12   * You should have received a copy of the GNU Lesser General Public License along with AceLogger.
13   * If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>.
14   */
15  package net.sourceforge.acelogger.execution;
16  
17  import java.text.MessageFormat;
18  import java.util.concurrent.ThreadFactory;
19  import java.util.concurrent.atomic.AtomicLong;
20  
21  /**
22   * A {@link ThreadFactory} that produces daemon threads.
23   * 
24   * @author Zardi (https://sourceforge.net/users/daniel_zardi)
25   * @version 1.0.0
26   * @since 1.0.0
27   */
28  public class DaemonThreadFactory implements ThreadFactory {
29  
30  	/**
31  	 * A counter to store thread count.
32  	 */
33  	private final AtomicLong counter;
34  
35  	/**
36  	 * The identifier of this thread factory.
37  	 */
38  	private String identifier;
39  
40  	/**
41  	 * Constructs a new DaemonThreadFactory with the supplied identifier.
42  	 * 
43  	 * @param identifier
44  	 *            The string that identifies this tread factory.
45  	 * @since 1.0.0
46  	 */
47  	public DaemonThreadFactory(String identifier) {
48  		counter = new AtomicLong();
49  		setIdentifier(identifier);
50  	}
51  
52  	/**
53  	 * Sets the string that identifies this object.
54  	 * 
55  	 * @param identifier
56  	 *            The identifier of this object.
57  	 * @since 1.0.0
58  	 */
59  	private void setIdentifier(String identifier) {
60  		this.identifier = identifier;
61  	}
62  
63  	/** {@inheritDoc} */
64  	public Thread newThread(Runnable command) {
65  		String threadName = MessageFormat.format(
66  				"{0}-executor-thread:{1}", identifier, counter.incrementAndGet());
67  		Thread newThread = new Thread(command, threadName);
68  		newThread.setDaemon(true);
69  		return newThread;
70  	}
71  }