Example usage for com.google.common.util.concurrent ThreadFactoryBuilder ThreadFactoryBuilder

List of usage examples for com.google.common.util.concurrent ThreadFactoryBuilder ThreadFactoryBuilder

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ThreadFactoryBuilder ThreadFactoryBuilder.

Prototype

public ThreadFactoryBuilder() 

Source Link

Document

Creates a new ThreadFactory builder.

Usage

From source file:org.onos.yangtools.util.concurrent.CachedThreadPoolExecutor.java

/**
 * Constructs an instance.//from ww  w .  j a  va  2  s .co m
 *
 * @param maximumPoolSize
 *            the maximum number of threads to allow in the pool. Threads will terminate after
 *            being idle for 60 seconds.
 * @param maximumQueueSize
 *            the capacity of the queue.
 * @param threadPrefix
 *            the name prefix for threads created by this executor.
 */
public CachedThreadPoolExecutor(final int maximumPoolSize, final int maximumQueueSize,
        final String threadPrefix) {
    // We're using a custom SynchronousQueue that has a backing bounded LinkedBlockingQueue.
    // We don't specify any core threads (first parameter) so, when a task is submitted,
    // the base class will always try to offer to the queue. If there is an existing waiting
    // thread, the offer will succeed and the task will be handed to the thread to execute. If
    // there's no waiting thread, either because there are no threads in the pool or all threads
    // are busy, the base class will try to create a new thread. If the maximum thread limit has
    // been reached, the task will be rejected. We specify a RejectedTaskHandler that tries
    // to offer to the backing queue. If that succeeds, the task will execute as soon as a
    // thread becomes available. If the offer fails to the backing queue, the task is rejected.
    super(0, maximumPoolSize, IDLE_TIMEOUT_IN_SEC, TimeUnit.SECONDS, new ExecutorQueue(maximumQueueSize));

    this.threadPrefix = Preconditions.checkNotNull(threadPrefix);
    this.maximumQueueSize = maximumQueueSize;

    setThreadFactory(
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat(this.threadPrefix + "-%d").build());

    executorQueue = (ExecutorQueue) super.getQueue();

    rejectedTaskHandler = new RejectedTaskHandler(executorQueue.getBackingQueue(),
            CountingRejectedExecutionHandler.newAbortPolicy());
    super.setRejectedExecutionHandler(rejectedTaskHandler);
}

From source file:org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.PipelineOrchestratorImpl.java

public PipelineOrchestratorImpl() {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("NV-PipelineOrch-%d").build();
    eventHandler = Executors.newSingleThreadExecutor(threadFactory);
    this.queue = new LinkedBlockingQueue<>();
    LOG.info("PipelineOrchestratorImpl constructor");
    start();//from   www .  j a va  2 s. c o  m
}

From source file:org.ngse.source.protobuf.ProtobufSource.java

@Override
public void start() {

    logger.info("Source starting");

    counterGroup.incrementAndGet("open.attempts");

    handlerService = Executors/* w w  w.  j a  va  2s  .c o  m*/
            .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("protobuf-handler-%d").build());

    try {
        SocketAddress bindPoint = new InetSocketAddress(hostName, port);

        serverSocket = ServerSocketChannel.open();
        serverSocket.socket().setReuseAddress(true);
        serverSocket.socket().bind(bindPoint);

        logger.info("Created serverSocket:{}", serverSocket);
    } catch (IOException e) {
        counterGroup.incrementAndGet("open.errors");
        logger.error("Unable to bind to socket. Exception follows.", e);
        throw new FlumeException(e);
    }

    AcceptHandler acceptRunnable = new AcceptHandler();
    acceptThreadShouldStop.set(false);
    acceptRunnable.counterGroup = counterGroup;
    acceptRunnable.handlerService = handlerService;
    acceptRunnable.shouldStop = acceptThreadShouldStop;
    acceptRunnable.source = this;
    acceptRunnable.serverSocket = serverSocket;

    acceptThread = new Thread(acceptRunnable);

    acceptThread.start();

    logger.debug("Source started");
    super.start();
}

From source file:org.apache.hadoop.hive.metastore.FileMetadataManager.java

public FileMetadataManager(ThreadLocalRawStore tlms, HiveConf conf) {
    this.tlms = tlms;
    this.conf = conf;
    int numThreads = HiveConf.getIntVar(conf, ConfVars.METASTORE_HBASE_FILE_METADATA_THREADS);
    this.threadPool = Executors.newFixedThreadPool(numThreads,
            new ThreadFactoryBuilder().setNameFormat("File-Metadata-%d").setDaemon(true).build());
}

From source file:com.kolich.pusachat.spring.beans.ChatRooms.java

@Override
public void afterPropertiesSet() throws Exception {
    chatRooms_ = new ConcurrentHashMap<UUID, ChatRoom>();
    // Reverse maps.
    keysToRooms_ = new ConcurrentHashMap<String, UUID>();
    roomsToKeys_ = new ConcurrentHashMap<UUID, String>();
    // Extract a configuration property that instructions how often
    // the chat room cleaner thread should wake up and remove "dead"
    // users from all of the rooms.
    final long removeInactiveUsersAfterMs = properties_.getRemoveInactiveAfter();
    // Setup a new thread factory builder.
    executor_ = newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("inactive-user-cleaner-%d").build());
    // Schedule a new cleaner at a "fixed" interval.
    executor_.scheduleAtFixedRate(new InactiveUserCleanerExecutor(this, removeInactiveUsersAfterMs), 0L, // initial delay
            removeInactiveUsersAfterMs, // repeat every
            MILLISECONDS); // units
}

From source file:com.kolich.blog.components.GitRepository.java

@Injectable
public GitRepository(@Required final ServletContext context, @Required final BlogEventBus eventBus)
        throws Exception {
    eventBus_ = eventBus;/*from   w  w w  . ja  va2s.  c  om*/
    executor_ = newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("blog-git-puller").build());
    final File repoDir = getRepoDir(context);
    logger__.info("Activated repository path: {}", repoDir.getCanonicalFile());
    // If were not in dev mode, and the clone path doesn't exist or we need to force clone from
    // scratch, do that now.
    final boolean clone = (!repoDir.exists() || shouldCloneOnStartup__);
    if (!isDevMode__ && clone) {
        logger__.info("Clone path does not exist, or we were asked to re-clone. Cloning from: {}",
                blogRepoCloneUrl__);
        // Recursively delete the existing clone of the repo, if it exists, and clone the repository.
        FileUtils.deleteDirectory(repoDir);
        Git.cloneRepository().setURI(blogRepoCloneUrl__).setDirectory(repoDir).setBranch("master").call();
    }
    // Construct a new pointer to the repository on disk.
    repo_ = new FileRepositoryBuilder().setWorkTree(repoDir).readEnvironment().build();
    git_ = new Git(repo_);
    logger__.info("Successfully initialized repository at: {}", repo_);
}

From source file:com.facebook.buck.event.listener.SuperConsoleEventBusListener.java

public SuperConsoleEventBusListener(Console console, Clock clock, ExecutionEnvironment executionEnvironment) {
    super(console, clock);

    this.threadsToRunningEvent = new ConcurrentHashMap<>(executionEnvironment.getAvailableCores());
    this.threadsToRunningStep = new ConcurrentHashMap<>(executionEnvironment.getAvailableCores());

    this.logEvents = new ConcurrentLinkedQueue<>();

    this.renderScheduler = Executors.newScheduledThreadPool(1,
            new ThreadFactoryBuilder().setNameFormat(getClass().getSimpleName() + "-%d").build());
    this.testFormatter = new TestResultFormatter(console.getAnsi());
}

From source file:org.apache.bookkeeper.proto.BookieClient.java

/**
 * @param args/* w w w.ja  v  a 2 s  .  c  o m*/
 * @throws IOException
 * @throws NumberFormatException
 * @throws InterruptedException
 */
public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException {
    if (args.length != 3) {
        System.err.println("USAGE: BookieClient bookieHost port ledger#");
        return;
    }
    WriteCallback cb = new WriteCallback() {

        public void writeComplete(int rc, long ledger, long entry, BookieSocketAddress addr, Object ctx) {
            Counter counter = (Counter) ctx;
            counter.dec();
            if (rc != 0) {
                System.out.println("rc = " + rc + " for " + entry + "@" + ledger);
            }
        }
    };
    Counter counter = new Counter();
    byte hello[] = "hello".getBytes(UTF_8);
    long ledger = Long.parseLong(args[2]);
    ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
    ClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(tfb.setNameFormat("BookKeeper-NIOBoss-%d").build()),
            Executors.newCachedThreadPool(tfb.setNameFormat("BookKeeper-NIOWorker-%d").build()));
    OrderedSafeExecutor executor = OrderedSafeExecutor.newBuilder().name("BookieClientWorker").numThreads(1)
            .build();
    BookieClient bc = new BookieClient(new ClientConfiguration(), channelFactory, executor);
    BookieSocketAddress addr = new BookieSocketAddress(args[0], Integer.parseInt(args[1]));

    for (int i = 0; i < 100000; i++) {
        counter.inc();
        bc.addEntry(addr, ledger, new byte[0], i, ChannelBuffers.wrappedBuffer(hello), cb, counter, 0);
    }
    counter.wait(0);
    System.out.println("Total = " + counter.total());
    channelFactory.releaseExternalResources();
    executor.shutdown();
}

From source file:com.facebook.buck.event.listener.RenderingConsole.java

public RenderingConsole(Clock clock, Console console) {
    this.clock = clock;
    this.console = console;
    this.ansi = console.getAnsi();
    this.renderScheduler = Executors.newScheduledThreadPool(1,
            new ThreadFactoryBuilder().setNameFormat(getClass().getSimpleName() + "-%d").build());
}