Java Code Examples for com.google.common.util.concurrent.ThreadFactoryBuilder.setNameFormat()

The following are Jave code examples for showing how to use setNameFormat() of the com.google.common.util.concurrent.ThreadFactoryBuilder class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ditb   File: TBoundedThreadPoolServer.java   View Source Code Vote up 6 votes
public TBoundedThreadPoolServer(Args options, ThriftMetrics metrics) {
  super(options);

  if (options.maxQueuedRequests > 0) {
    this.callQueue = new CallQueue(
        new LinkedBlockingQueue<Call>(options.maxQueuedRequests), metrics);
  } else {
    this.callQueue = new CallQueue(new SynchronousQueue<Call>(), metrics);
  }

  ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
  tfb.setDaemon(true);
  tfb.setNameFormat("thrift-worker-%d");
  executorService =
      new ThreadPoolExecutor(options.minWorkerThreads,
          options.maxWorkerThreads, options.threadKeepAliveTimeSec,
          TimeUnit.SECONDS, this.callQueue, tfb.build());
  serverOptions = options;
}
 
Example 2
Project: ditb   File: BulkAssigner.java   View Source Code Vote up 6 votes
/**
 * Run the bulk assign.
 * 
 * @param sync
 *          Whether to assign synchronously.
 * @throws InterruptedException
 * @return True if done.
 * @throws IOException
 */
public boolean bulkAssign(boolean sync) throws InterruptedException,
    IOException {
  boolean result = false;
  ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
  builder.setDaemon(true);
  builder.setNameFormat(getThreadNamePrefix() + "-%1$d");
  builder.setUncaughtExceptionHandler(getUncaughtExceptionHandler());
  int threadCount = getThreadCount();
  java.util.concurrent.ExecutorService pool =
    Executors.newFixedThreadPool(threadCount, builder.build());
  try {
    populatePool(pool);
    // How long to wait on empty regions-in-transition.  If we timeout, the
    // RIT monitor should do fixup.
    if (sync) result = waitUntilDone(getTimeoutOnRIT());
  } finally {
    // We're done with the pool.  It'll exit when its done all in queue.
    pool.shutdown();
  }
  return result;
}
 
Example 3
Project: ditb   File: ThriftServer.java   View Source Code Vote up 5 votes
private static ExecutorService createExecutor(
    int workerThreads, ThriftMetrics metrics) {
  CallQueue callQueue = new CallQueue(
      new LinkedBlockingQueue<Call>(), metrics);
  ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
  tfb.setDaemon(true);
  tfb.setNameFormat("thrift2-worker-%d");
  ThreadPoolExecutor pool = new ThreadPoolExecutor(workerThreads, workerThreads,
          Long.MAX_VALUE, TimeUnit.SECONDS, callQueue, tfb.build());
  pool.prestartAllCoreThreads();
  return pool;
}
 
Example 4
Project: ditb   File: ThriftServerRunner.java   View Source Code Vote up 5 votes
ExecutorService createExecutor(BlockingQueue<Runnable> callQueue,
                               int minWorkers, int maxWorkers) {
  ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
  tfb.setDaemon(true);
  tfb.setNameFormat("thrift-worker-%d");
  return new ThreadPoolExecutor(minWorkers, maxWorkers,
          Long.MAX_VALUE, TimeUnit.SECONDS, callQueue, tfb.build());
}
 
Example 5
Project: ditb   File: ReplicationSourceManager.java   View Source Code Vote up 5 votes
/**
 * Creates a replication manager and sets the watch on all the other registered region servers
 * @param replicationQueues the interface for manipulating replication queues
 * @param replicationPeers
 * @param replicationTracker
 * @param conf the configuration to use
 * @param server the server for this region server
 * @param fs the file system to use
 * @param logDir the directory that contains all wal directories of live RSs
 * @param oldLogDir the directory where old logs are archived
 * @param clusterId
 */
public ReplicationSourceManager(final ReplicationQueues replicationQueues,
    final ReplicationPeers replicationPeers, final ReplicationTracker replicationTracker,
    final Configuration conf, final Server server, final FileSystem fs, final Path logDir,
    final Path oldLogDir, final UUID clusterId) {
  //CopyOnWriteArrayList is thread-safe.
  //Generally, reading is more than modifying.
  this.sources = new CopyOnWriteArrayList<ReplicationSourceInterface>();
  this.replicationQueues = replicationQueues;
  this.replicationPeers = replicationPeers;
  this.replicationTracker = replicationTracker;
  this.server = server;
  this.walsById = new HashMap<String, Map<String, SortedSet<String>>>();
  this.walsByIdRecoveredQueues = new ConcurrentHashMap<String, Map<String, SortedSet<String>>>();
  this.oldsources = new CopyOnWriteArrayList<ReplicationSourceInterface>();
  this.conf = conf;
  this.fs = fs;
  this.logDir = logDir;
  this.oldLogDir = oldLogDir;
  this.sleepBeforeFailover =
      conf.getLong("replication.sleep.before.failover", 30000); // 30 seconds
  this.clusterId = clusterId;
  this.replicationTracker.registerListener(this);
  this.replicationPeers.getAllPeerIds();
  // It's preferable to failover 1 RS at a time, but with good zk servers
  // more could be processed at the same time.
  int nbWorkers = conf.getInt("replication.executor.workers", 1);
  // use a short 100ms sleep since this could be done inline with a RS startup
  // even if we fail, other region servers can take care of it
  this.executor = new ThreadPoolExecutor(nbWorkers, nbWorkers,
      100, TimeUnit.MILLISECONDS,
      new LinkedBlockingQueue<Runnable>());
  ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
  tfb.setNameFormat("ReplicationExecutor-%d");
  tfb.setDaemon(true);
  this.executor.setThreadFactory(tfb.build());
  this.rand = new Random();
  this.latestPaths = Collections.synchronizedSet(new HashSet<Path>());
}
 
Example 6
Project: ditb   File: ExecutorService.java   View Source Code Vote up 5 votes
protected Executor(String name, int maxThreads,
    final Map<EventType, EventHandlerListener> eventHandlerListeners) {
  this.id = seqids.incrementAndGet();
  this.name = name;
  this.eventHandlerListeners = eventHandlerListeners;
  // create the thread pool executor
  this.threadPoolExecutor = new TrackingThreadPoolExecutor(
      maxThreads, maxThreads,
      keepAliveTimeInMillis, TimeUnit.MILLISECONDS, q);
  // name the threads for this threadpool
  ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
  tfb.setNameFormat(this.name + "-%d");
  this.threadPoolExecutor.setThreadFactory(tfb.build());
}
 
Example 7
Project: bench   File: WatcherScheduler.java   View Source Code Vote up 4 votes
private static ScheduledExecutorService initScheduler(final String nameFormat) {
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
    builder.setDaemon(true);
    builder.setNameFormat(nameFormat);
    return Executors.newScheduledThreadPool(1, builder.build());
}
 
Example 8
Project: TFWebSock   File: ServerMain.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    // must do this first for logback
    InternalLoggerFactory.setDefaultFactory( new Slf4JLoggerFactory( ));

    // args[0] should be the path of the transficc.props properties file
    String propsFilePath = args[0];
    Properties props = new Properties( );

    // load up the props for socket and DB config
    File pfile = new File( propsFilePath);
    logger.info( "Loading config from: " + propsFilePath);
    InputStream istrm = new FileInputStream( propsFilePath);
    props.load( istrm);
    String sport = props.getProperty( "SocketServerPort", "8080");
    logger.info( "Binding to port: " + sport);
    int port = Integer.parseInt( sport);

    // Create the transficc client, and the Q it uses to send events including
    // market data back to the thread that pushes updates on the web sockets.
    // Also an executor to provide a thread to run the TFClient. We keep a ref
    // to the transficc service so we can pass it to the web socket handler.
    LinkedBlockingQueue<JSON.Message> outQ = new LinkedBlockingQueue<JSON.Message>( );
    TFClient tfc = new TFClient( props, outQ);
    TransficcService tfs = tfc.GetService( );
    // need an executor for the thread that will intermittently send data to the client
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder( );
    builder.setDaemon( true);
    builder.setNameFormat( "transficc-%d");
    ExecutorService transficcExecutor = Executors.newSingleThreadExecutor( builder.build( ));
    FutureTask<String> transficcTask = new FutureTask<String>( tfc);
    transficcExecutor.execute( transficcTask);

    // Now we can create the pusher object and thread, which consumes the event
    // on the outQ. Those events originate with TFClient callbacks from transficc,
    // and also incoming websock events like subscription requests.
    WebSockPusher pusher = new WebSockPusher( props, outQ, tfs);
    ExecutorService pusherExecutor = Executors.newSingleThreadExecutor( builder.build( ));
    FutureTask<String> pusherTask = new FutureTask<String>( pusher);
    pusherExecutor.execute( pusherTask);

    // Compose the server components...
    EventLoopGroup bossGroup = new NioEventLoopGroup( 1);
    EventLoopGroup workerGroup = new NioEventLoopGroup( );
    try {
        ServerBootstrap b = new ServerBootstrap( );
        LoggingHandler lh = new LoggingHandler(LogLevel.INFO);
        ChannelInitializer ci = new ChannelInitializer<SocketChannel>( ) {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast("encoder", new HttpResponseEncoder());
                p.addLast("decoder", new HttpRequestDecoder());
                p.addLast("aggregator", new HttpObjectAggregator(65536));
                p.addLast("handler", new WebSocketHandler( props, outQ));
            }
        };
        b.group( bossGroup, workerGroup).channel( NioServerSocketChannel.class).handler( lh).childHandler( ci);
        // Fire up the server...
        ChannelFuture f = b.bind( port).sync( );
        logger.info( "Server started");
        // Wait until the server socket is closed.
        f.channel( ).closeFuture( ).sync( );
    }
    finally {
        logger.info( "Server shutdown started");
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully( );
        workerGroup.shutdownGracefully();
        logger.info( "Server shutdown completed");
    }
}