Merge branch 'master' of ../controller
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / concurrent / ThreadFactoryProvider.java
1 /*
2  * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.util.concurrent;
9
10 import com.google.common.util.concurrent.ThreadFactoryBuilder;
11 import java.util.Optional;
12 import java.util.concurrent.ThreadFactory;
13 import org.immutables.value.Value;
14 import org.slf4j.Logger;
15
16 /**
17  * Builder for {@link ThreadFactory}. Easier to use than the
18  * {@link ThreadFactoryBuilder}, because it enforces setting all required
19  * properties through a staged builder.
20  *
21  * @author Michael Vorburger.ch
22  */
23 @Value.Immutable
24 @Value.Style(stagedBuilder = true)
25 public abstract class ThreadFactoryProvider {
26
27     // This class is also available in infrautils (but yangtools cannot depend on infrautils)
28     // as org.opendaylight.infrautils.utils.concurrent.ThreadFactoryProvider
29
30     public static ImmutableThreadFactoryProvider.NamePrefixBuildStage builder() {
31         return ImmutableThreadFactoryProvider.builder();
32     }
33
34     /**
35      * Prefix for threads from this factory. For example, "rpc-pool", to create
36      * "rpc-pool-1/2/3" named threads. Note that this is a prefix, not a format,
37      * so you pass just "rpc-pool" instead of e.g. "rpc-pool-%d".
38      */
39     @Value.Parameter public abstract String namePrefix();
40
41     /**
42      * Logger used to log uncaught exceptions from new threads created via this factory.
43      */
44     @Value.Parameter public abstract Logger logger();
45
46     /**
47      * Priority for new threads from this factory.
48      */
49     @Value.Parameter public abstract Optional<Integer> priority();
50
51     /**
52      * Daemon or not for new threads created via this factory.
53      * <b>NB: Defaults to true.</b>
54      */
55     @Value.Default public boolean daemon() {
56         return true;
57     }
58
59     public ThreadFactory get() {
60         ThreadFactoryBuilder guavaBuilder = new ThreadFactoryBuilder();
61         guavaBuilder.setNameFormat(namePrefix() + "-%d");
62         guavaBuilder.setUncaughtExceptionHandler(LoggingThreadUncaughtExceptionHandler.toLogger(logger()));
63         guavaBuilder.setDaemon(daemon());
64         priority().ifPresent(guavaBuilder::setPriority);
65         logger().info("ThreadFactory created: {}", namePrefix());
66         return guavaBuilder.build();
67     }
68 }