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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12 import java.util.Optional;
13 import java.util.concurrent.ThreadFactory;
14 import javax.annotation.processing.Generated;
15 import org.immutables.value.Value;
16 import org.slf4j.Logger;
19 * Builder for {@link ThreadFactory}. Easier to use than the
20 * {@link ThreadFactoryBuilder}, because it enforces setting all required
21 * properties through a staged builder.
23 * @author Michael Vorburger.ch
26 @Value.Style(stagedBuilder = true, allowedClasspathAnnotations = {
27 SuppressWarnings.class, Generated.class, SuppressFBWarnings.class,
29 public abstract class ThreadFactoryProvider {
31 // This class is also available in infrautils (but yangtools cannot depend on infrautils)
32 // as org.opendaylight.infrautils.utils.concurrent.ThreadFactoryProvider
34 public static ImmutableThreadFactoryProvider.NamePrefixBuildStage builder() {
35 return ImmutableThreadFactoryProvider.builder();
39 * Prefix for threads from this factory. For example, "rpc-pool", to create
40 * "rpc-pool-1/2/3" named threads. Note that this is a prefix, not a format,
41 * so you pass just "rpc-pool" instead of e.g. "rpc-pool-%d".
43 @Value.Parameter public abstract String namePrefix();
46 * Logger used to log uncaught exceptions from new threads created via this factory.
48 @Value.Parameter public abstract Logger logger();
51 * Priority for new threads from this factory.
53 @Value.Parameter public abstract Optional<Integer> priority();
56 * Daemon or not for new threads created via this factory.
57 * <b>NB: Defaults to true.</b>
59 @Value.Default public boolean daemon() {
63 public ThreadFactory get() {
64 ThreadFactoryBuilder guavaBuilder = new ThreadFactoryBuilder()
65 .setNameFormat(namePrefix() + "-%d")
66 .setUncaughtExceptionHandler((thread, exception)
67 -> logger().error("Thread terminated due to uncaught exception: {}", thread.getName(), exception))
69 priority().ifPresent(guavaBuilder::setPriority);
70 logger().info("ThreadFactory created: {}", namePrefix());
71 return guavaBuilder.build();