Example usage for java.util.concurrent Executors newCachedThreadPool

List of usage examples for java.util.concurrent Executors newCachedThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newCachedThreadPool.

Prototype

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) 

Source Link

Document

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available, and uses the provided ThreadFactory to create new threads when needed.

Usage

From source file:com.canoo.dolphin.client.ClientConfiguration.java

/**
 * Default constructor of a client configuration
 *
 * @param serverEndpoint the Dolphin Platform server url
 * @param uiThreadHandler the ui thread handler
 *///from   www . j  a va  2s  .  c  o  m
public ClientConfiguration(URL serverEndpoint, UiThreadHandler uiThreadHandler) {
    this.serverEndpoint = Assert.requireNonNull(serverEndpoint, "serverEndpoint");
    this.uiThreadHandler = Assert.requireNonNull(uiThreadHandler, "uiThreadHandler");
    this.dolphinLogLevel = Level.SEVERE;
    this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;

    httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    dolphinPlatformThreadFactory = new DolphinPlatformThreadFactoryImpl();
    backgroundExecutor = Executors.newCachedThreadPool(dolphinPlatformThreadFactory);
}

From source file:com.mgmtp.perfload.core.clientserver.client.DefaultClient.java

/**
 * Creates a new instance that talks to a {@link DefaultServer} on the specified host and port.
 * //ww w .jav a2s  .  com
 * @param clientId
 *            A unique id. No two clients with the same id can access the same
 *            {@link DefaultServer}
 * @param host
 *            The host the {@link DefaultServer} runs on
 * @param port
 *            The port the {@link DefaultServer} runs on
 */
public DefaultClient(final String clientId, final String host, final int port) {
    this.clientId = clientId;
    this.host = host;
    this.port = port;

    // Configure the client.
    bootstrap = new ClientBootstrap(
            new OioClientSocketChannelFactory(Executors.newCachedThreadPool(new DaemonThreadFactory())));

    // Set up the pipeline factory.
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override
        public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(new ObjectEncoder(ENCODER_ESTIMATED_LENGTH),
                    new ObjectDecoder(DECODER_ESTIMATED_LENGTH, ClassResolvers.weakCachingResolver(null)),
                    new ClientHandshakeHandler(new Handshake(clientId), HANDSHAKE_TIMEOUT_MILLIS),
                    clientHandler);
        }
    });

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("soTimeout", 10000L);
}

From source file:com.proofpoint.event.blackhole.TestServer.java

@BeforeMethod
public void setup() throws Exception {
    Map<String, String> properties = ImmutableMap.<String, String>builder()
            .put("blackhole.announcement", "blackhole").build();

    Injector injector = Guice.createInjector(new ConfigurationModule(new ConfigurationFactory(properties)),
            new TestingNodeModule(), new InMemoryEventModule(), new TestingHttpServerModule(), new JsonModule(),
            new JaxrsModule(), new MainModule());
    server = injector.getInstance(TestingHttpServer.class);
    eventClient = (InMemoryEventClient) injector.getInstance(EventClient.class);
    blackholeResource = injector.getInstance(BlackholeResource.class);

    server.start();//from  ww  w .ja v a  2 s. c  o  m
    executor = Executors.newCachedThreadPool(
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Test-Server-%s").build());
    client = new ApacheHttpClient();
}

From source file:cloudlens.notebook.JSInterpreter.java

public InterpreterResult interpret(Callable<BlockObject> task, CL cl) {
    if (cl.out instanceof ByteArrayOutputStream) {
        ((ByteArrayOutputStream) cl.out).reset();
    }/*from  w  w  w  .  j ava 2s. c  o  m*/
    if (cl.err instanceof ByteArrayOutputStream) {
        ((ByteArrayOutputStream) cl.err).reset();
    }
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r) {
                @Override
                public void interrupt() {
                    stop();
                }
            };
        }
    });
    cl.future = executor.submit(task);
    final Gson gson = new GsonBuilder().create();
    try {
        final BlockObject obj = cl.future.get();
        cl.outWriter.flush();
        cl.errWriter.flush();
        if (obj instanceof InterpreterResult) {
            return (InterpreterResult) obj;
        }
        if (cl.out instanceof ByteArrayOutputStream && ((ByteArrayOutputStream) cl.out).size() == 0) {
            if (null != obj && obj.isMapArray()) {
                final Map<String, Map<String, Object>> entries = obj.asMapArray();
                cl.outWriter.print("%table\n");
                int i = 0;
                for (final Map<?, ?> entry : entries.values()) {
                    cl.outWriter.print("\n");
                    if (++i > maxResult) {
                        cl.outWriter.println(
                                "%html <font color=red>Results are limited by zeppelin.cloudlens.maxResult = "
                                        + maxResult + ".</font>");
                        break;
                    }
                    for (final Map.Entry<?, ?> field : entry.entrySet()) {
                        cl.outWriter.print("%html <font color=blue>"
                                + StringEscapeUtils.escapeHtml4(field.getKey().toString()) + "</font>:"
                                + StringEscapeUtils.escapeHtml4(gson.toJson(field.getValue()).toString())
                                + "\t");
                    }
                }
            } else {
                cl.engine.bind("__Result__", obj);
                cl.engine.eval(
                        "print(JSON.stringify(__Result__, function(key, val) { if (typeof val === 'function') return val + ''; return val; }, 2))");
            }
        }
        // }
    } catch (final InterruptedException |

            ExecutionException e) {
        return new InterpreterResult(Code.ERROR, InterpreterUtils.getMostRelevantMessage(e));
    } finally {
        cl.outWriter.flush();
        cl.errWriter.flush();
        executor.shutdownNow();
    }
    return new InterpreterResult(Code.SUCCESS, cl.out.toString());
}

From source file:com.hellblazer.jackal.configuration.ThreadConfig.java

@Bean(name = "gossipDispatchers")
@Lazy//from w w  w.j  a  v  a2  s .  c o m
@Autowired
public ExecutorService gossipDispatchers(Identity partitionIdentity) {
    final int id = partitionIdentity.id;
    return Executors.newCachedThreadPool(new ThreadFactory() {
        int count = 0;

        @Override
        public Thread newThread(Runnable target) {
            Thread t = new Thread(target, String.format("Gossip Dispatcher[%s] for node[%s]", count++, id));
            t.setDaemon(true);
            t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    log.error(String.format("Exception on %s", t), e);
                }
            });
            return t;
        }
    });
}

From source file:com.linkedin.pinot.controller.ControllerStarter.java

public ControllerStarter(ControllerConf conf) {
    config = conf;/* w  w w .  j av  a 2  s .  co m*/
    component = new Component();
    controllerRestApp = new ControllerRestApplication(config.getQueryConsole());
    helixResourceManager = new PinotHelixResourceManager(config);
    retentionManager = new RetentionManager(helixResourceManager,
            config.getRetentionControllerFrequencyInSeconds());
    _metricsRegistry = new MetricsRegistry();
    ValidationMetrics validationMetrics = new ValidationMetrics(_metricsRegistry);
    validationManager = new ValidationManager(validationMetrics, helixResourceManager, config);
    realtimeSegmentsManager = new PinotRealtimeSegmentManager(helixResourceManager);
    segmentStatusChecker = new SegmentStatusChecker(helixResourceManager, config);
    executorService = Executors.newCachedThreadPool(
            new ThreadFactoryBuilder().setNameFormat("restlet-multiget-thread-%d").build());
}

From source file:com.alibaba.jstorm.message.netty.NettyClientSync.java

@SuppressWarnings("rawtypes")
NettyClientSync(Map storm_conf, ChannelFactory factory, ScheduledExecutorService scheduler, String host,
        int port, ReconnectRunnable reconnector) {
    super(storm_conf, factory, scheduler, host, port, reconnector);

    batchQueue = new ConcurrentLinkedQueue<MessageBatch>();

    WaitStrategy waitStrategy = (WaitStrategy) Utils
            .newInstance((String) storm_conf.get(Config.TOPOLOGY_DISRUPTOR_WAIT_STRATEGY));

    disruptorQueue = DisruptorQueue.mkInstance(name, ProducerType.MULTI, MAX_SEND_PENDING * 8, waitStrategy);
    disruptorQueue.consumerStarted();//w w  w . j a v a2 s .  co  m

    if (connectMyself == false) {
        registerSyncMetrics();
    }

    Runnable trigger = new Runnable() {
        @Override
        public void run() {
            trigger();
        }
    };

    scheduler.scheduleAtFixedRate(trigger, 10, 1, TimeUnit.SECONDS);

    /**
     * In sync mode, it can't directly use common factory, it will occur problem when client close and restart
     */
    ThreadFactory bossFactory = new NettyRenameThreadFactory(
            MetricDef.NETTY_CLI + JStormServerUtils.getName(host, port) + "-boss");
    bossExecutor = Executors.newCachedThreadPool(bossFactory);
    ThreadFactory workerFactory = new NettyRenameThreadFactory(
            MetricDef.NETTY_CLI + JStormServerUtils.getName(host, port) + "-worker");
    workerExecutor = Executors.newCachedThreadPool(workerFactory);

    clientChannelFactory = new NioClientSocketChannelFactory(bossExecutor, workerExecutor, 1);

    start();

    LOG.info(this.toString());
}

From source file:de.ufinke.cubaja.sort.SortManager.java

public SortManager(SortConfig config, Comparator<?> comparator) {

    myId = getId();/*from  ww w  .  j a v  a  2s  .  co m*/

    this.config = config;
    this.comparator = comparator;

    if (config.isLog()) {
        logger = LogFactory.getLog(Sorter.class);
        logPrefix = "Sort#" + myId + ": ";
        stopwatch = new Stopwatch();
    } else {
        logger = null;
        logPrefix = null;
        stopwatch = null;
    }
    logInterval = config.getLogInterval() * 1000;

    algorithm = config.getAlgorithm();

    int blockSize = config.getBlockSize();
    if (blockSize == 0) {
        blockSize = DEFAULT_BLOCK_SIZE;
    }
    if (blockSize < MINIMUM_BLOCK_SIZE) {
        blockSize = MINIMUM_BLOCK_SIZE;
    }
    this.blockSize = blockSize;

    int runSize = config.getRunSize();
    if (runSize == 0) {
        runSize = DEFAULT_RUN_SIZE;
    }
    if (runSize < MINIMUM_RUN_SIZE) {
        runSize = MINIMUM_RUN_SIZE;
    }
    this.runSize = runSize;

    int arrayCount = 1;
    int arraySize = runSize;
    while (arraySize > MAX_ARRAY_SIZE) {
        arraySize = arraySize >> 1;
        arrayCount = arrayCount << 1;
    }
    this.arrayCount = arrayCount;
    this.arraySize = arraySize;

    int queueCapacity = (arrayCount >> 1) + (arrayCount >> 4) + 1;
    sortQueue = new ArrayBlockingQueue<Request>(queueCapacity);
    fileQueue = new ArrayBlockingQueue<Request>(queueCapacity);
    mainQueue = new ArrayBlockingQueue<Request>(queueCapacity);

    executor = Executors.newCachedThreadPool(createThreadFactory());

    if (isDebug()) {
        putCount = new AtomicLong();
        getCount = new AtomicLong();
        debug("sortOpen", runSize, blockSize, algorithm.getClass().getName());
        if (isTrace()) {
            initTimer(logger, logPrefix, "sortPut", putCount);
        }
    }
}

From source file:com.ganji.cateye.flume.kestrel.KestrelRpcClient.java

License:asdf

public KestrelRpcClient() {
    stateLock = new ReentrantLock(true);
    connState = State.INIT;//ww w.  j  a  v  a 2  s .  c o m

    threadCounter = new AtomicLong(0);
    // OK to use cached threadpool, because this is simply meant to timeout
    // the calls - and is IO bound.
    callTimeoutPool = Executors.newCachedThreadPool(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(KestrelRpcClient.this.sinkName + "-" + String.valueOf(threadCounter.incrementAndGet()));
            return t;
        }
    });
}

From source file:com.hypersocket.netty.NettyServer.java

@Override
protected void doStart() throws IOException {

    System.setProperty("hypersocket.netty.debug", "true");

    clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            bossExecutor = Executors.newCachedThreadPool(new NettyThreadFactory()),
            workerExecutors = Executors.newCachedThreadPool(new NettyThreadFactory())));

    clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("handler", new SocketForwardingWebsocketClientHandler());
            return pipeline;
        }/*  www.ja  v a 2  s.  com*/
    });

    // Configure the server.
    serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool()));

    // Set up the event pipeline factory.
    serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            if (Boolean.getBoolean("hypersocket.netty.debug")) {
                pipeline.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG));
            }
            pipeline.addLast("ipFilter", ipFilterHandler);
            pipeline.addLast("channelMonitor", monitorChannelHandler);
            pipeline.addLast("switcherA",
                    new SSLSwitchingHandler(NettyServer.this, getHttpPort(), getHttpsPort()));
            return pipeline;
        }
    });

    serverBootstrap.setOption("child.receiveBufferSize", 1048576);
    serverBootstrap.setOption("child.sendBufferSize", 1048576);
    serverBootstrap.setOption("backlog", 5000);

    httpChannels = new HashSet<Channel>();
    httpsChannels = new HashSet<Channel>();

    bindInterface(getHttpPort(), httpChannels);
    bindInterface(getHttpsPort(), httpsChannels);

    if (httpChannels.size() == 0 && httpsChannels.size() == 0) {
        throw new IOException("Failed to startup any listening interfaces!");
    }
}