2 * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.util.concurrent;
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;
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.
21 * @author Michael Vorburger.ch
24 @Value.Style(stagedBuilder = true)
25 public abstract class ThreadFactoryProvider {
27 // This class is also available in infrautils (but yangtools cannot depend on infrautils)
28 // as org.opendaylight.infrautils.utils.concurrent.ThreadFactoryProvider
30 public static ImmutableThreadFactoryProvider.NamePrefixBuildStage builder() {
31 return ImmutableThreadFactoryProvider.builder();
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".
39 @Value.Parameter public abstract String namePrefix();
42 * Logger used to log uncaught exceptions from new threads created via this factory.
44 @Value.Parameter public abstract Logger logger();
47 * Priority for new threads from this factory.
49 @Value.Parameter public abstract Optional<Integer> priority();
52 * Daemon or not for new threads created via this factory.
53 * <b>NB: Defaults to true.</b>
55 @Value.Default public boolean daemon() {
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();