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() 

Source Link

Document

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.

Usage

From source file:com.gitblit.plugin.glip.Glip.java

Glip(IRuntimeManager runtimeManager) {
    this.runtimeManager = runtimeManager;
    this.taskPool = Executors.newCachedThreadPool();
}

From source file:edu.cornell.med.icb.R.RUtils.java

public static void main(final String[] args) throws ParseException, ConfigurationException {
    final Options options = new Options();

    final Option helpOption = new Option("h", "help", false, "Print this message");
    options.addOption(helpOption);//from  w w w .  ja va2s .  co m

    final Option startupOption = new Option(Mode.startup.name(), Mode.startup.name(), false,
            "Start Rserve process");
    final Option shutdownOption = new Option(Mode.shutdown.name(), Mode.shutdown.name(), false,
            "Shutdown Rserve process");
    final Option validateOption = new Option(Mode.validate.name(), Mode.validate.name(), false,
            "Validate that Rserve processes are running");

    final OptionGroup optionGroup = new OptionGroup();
    optionGroup.addOption(startupOption);
    optionGroup.addOption(shutdownOption);
    optionGroup.addOption(validateOption);
    optionGroup.setRequired(true);
    options.addOptionGroup(optionGroup);

    final Option portOption = new Option("port", "port", true,
            "Use specified port to communicate with the Rserve process");
    portOption.setArgName("port");
    portOption.setType(int.class);
    options.addOption(portOption);

    final Option hostOption = new Option("host", "host", true,
            "Communicate with the Rserve process on the given host");
    hostOption.setArgName("hostname");
    hostOption.setType(String.class);
    options.addOption(hostOption);

    final Option userOption = new Option("u", "username", true, "Username to send to the Rserve process");
    userOption.setArgName("username");
    userOption.setType(String.class);
    options.addOption(userOption);

    final Option passwordOption = new Option("p", "password", true, "Password to send to the Rserve process");
    passwordOption.setArgName("password");
    passwordOption.setType(String.class);
    options.addOption(passwordOption);

    final Option configurationOption = new Option("c", "configuration", true,
            "Configuration file or url to read from");
    configurationOption.setArgName("configuration");
    configurationOption.setType(String.class);
    options.addOption(configurationOption);

    final Parser parser = new BasicParser();
    final CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        usage(options);
        throw e;
    }

    int exitStatus = 0;
    if (commandLine.hasOption("h")) {
        usage(options);
    } else {
        Mode mode = null;
        for (final Mode potentialMode : Mode.values()) {
            if (commandLine.hasOption(potentialMode.name())) {
                mode = potentialMode;
                break;
            }
        }

        final ExecutorService threadPool = Executors.newCachedThreadPool();

        if (commandLine.hasOption("configuration")) {
            final String configurationFile = commandLine.getOptionValue("configuration");
            LOG.info("Reading configuration from " + configurationFile);
            XMLConfiguration configuration;
            try {
                final URL configurationURL = new URL(configurationFile);
                configuration = new XMLConfiguration(configurationURL);
            } catch (MalformedURLException e) {
                // resource is not a URL: attempt to get the resource from a file
                LOG.debug("Configuration is not a valid url");
                configuration = new XMLConfiguration(configurationFile);
            }

            configuration.setValidating(true);
            final int numberOfRServers = configuration.getMaxIndex("RConfiguration.RServer") + 1;
            boolean failed = false;
            for (int i = 0; i < numberOfRServers; i++) {
                final String server = "RConfiguration.RServer(" + i + ")";
                final String host = configuration.getString(server + "[@host]");
                final int port = configuration.getInt(server + "[@port]",
                        RConfigurationUtils.DEFAULT_RSERVE_PORT);
                final String username = configuration.getString(server + "[@username]");
                final String password = configuration.getString(server + "[@password]");
                final String command = configuration.getString(server + "[@command]", DEFAULT_RSERVE_COMMAND);

                if (executeMode(mode, threadPool, host, port, username, password, command) != 0) {
                    failed = true; // we have other hosts to check so keep a failed state
                }
            }
            if (failed) {
                exitStatus = 3;
            }
        } else {
            final String host = commandLine.getOptionValue("host", "localhost");
            final int port = Integer.valueOf(commandLine.getOptionValue("port", "6311"));
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");

            exitStatus = executeMode(mode, threadPool, host, port, username, password, null);
        }
        threadPool.shutdown();
    }

    System.exit(exitStatus);
}

From source file:aos.camel.JavaFutureTest.java

@Test
public void testFutureWithDone() throws Exception {
    // this is the task we want to execute async
    // usually the task is something that takes
    // some time to do
    Callable<String> task = new Callable<String>() {
        public String call() throws Exception {
            // do something that takes some time
            LOG.info("Starting to process task");
            Thread.sleep(5000);//from w w w .j a v  a 2  s  .  c  o  m
            LOG.info("Task is now done");
            return "Camel rocks";
        }
    };

    // this is the thread pool we will use
    ExecutorService executor = Executors.newCachedThreadPool();

    // now submit the task to the thread pool
    // and get the Future handle back so we can later get the result
    LOG.info("Submitting task to ExecutorService");
    Future<String> future = executor.submit(task);
    LOG.info("Task submitted and we got a Future handle");

    // test when we are done
    boolean done = false;
    while (!done) {
        done = future.isDone();
        LOG.info("Is the task done? " + done);
        if (!done) {
            Thread.sleep(2000);
        }
    }

    // and get the answer
    String answer = future.get();
    LOG.info("The answer is: " + answer);
}

From source file:dbseer.comp.process.live.LiveLogProcessor.java

public void start() throws Exception {
    liveLogExecutor = Executors.newCachedThreadPool();
    sysStartTime = 0;//w  w  w  .j  a  v  a  2 s . co m
    txStartTime = 0;

    // check live directory
    File liveDir = new File(dir);
    if (!liveDir.exists()) {
        // create directories if it does not exist.
        liveDir.mkdirs();
    }

    // start sys log processors
    servers = serverStr.split(MiddlewareConstants.SERVER_STRING_DELIMITER);
    for (String server : servers) {
        FileUtils.forceMkdir(new File(dir + File.separator + server));
        FileUtils.cleanDirectory(new File(dir + File.separator + server));
        File sysFile = new File(dir + File.separator + "sys.log." + server);
        SystemLogProcessor sysLogProcessor;
        if (DBSeerGUI.osType == DBSeerConstants.OS_LINUX) {
            sysLogProcessor = new DstatSystemLogProcessor(dir + File.separator + server, this);
        } else {
            sysLogProcessor = new DstatSystemLogProcessor(dir + File.separator + server, this);
        }
        sysLogProcessor.initialize();
        LiveLogTailer sysLogTailerListener = new LiveLogTailer(sysLogProcessor);
        LogTailer sysLogTailer = new LogTailer(sysFile, sysLogTailerListener, 250, 0, false);

        liveLogExecutor.submit(sysLogTailer);
    }

    // start tx log processors
    TransactionLogProcessor txLogProcessor;
    if (DBSeerGUI.databaseType == DBSeerConstants.DB_MYSQL) {
        txLogProcessor = new MySQLTransactionLogProcessor(DBSeerGUI.settings.mysqlLogDelimiter,
                DBSeerGUI.settings.mysqlQueryDelimiter);
    } else {
        txLogProcessor = new MySQLTransactionLogProcessor(DBSeerGUI.settings.mysqlLogDelimiter,
                DBSeerGUI.settings.mysqlQueryDelimiter);
    }
    File txLogFile = new File(dir + File.separator + "tx.log");
    LiveLogTailer txLogTailerListener = new LiveLogTailer(txLogProcessor);
    LogTailer txLogTailer = new LogTailer(txLogFile, txLogTailerListener, 250, 0, false);

    transactionLogWriter = new TransactionLogWriter(dir, servers, DBSeerGUI.liveMonitorInfo, this);
    transactionLogWriter.initialize();

    liveTransactionLogWriter = new LiveTransactionLogWriter(txLogProcessor, transactionLogWriter);
    liveMonitor = new LiveMonitor();

    liveLogExecutor.submit(txLogTailer);
    liveLogExecutor.submit(liveTransactionLogWriter);
    liveLogExecutor.submit(liveMonitor);
    this.isStarted = true;
}

From source file:com.github.jarlakxen.embedphantomjs.executor.PhantomJSFileExecutor.java

public PhantomJSFileExecutor(PhantomJSReference phantomReference, ExecutorService executorService,
        ExecutionTimeout executionTimeout) {
    this.phantomReference = phantomReference;
    this.executionTimeout = executionTimeout;
    this.processExecutorService = MoreExecutors.listeningDecorator(executorService);
    this.timeoutExecutorService = Executors.newCachedThreadPool();
}

From source file:com.linkedin.r2.filter.compression.stream.TestStreamingCompression.java

@BeforeClass
public void setup() {
    _executor = Executors.newCachedThreadPool();
}

From source file:org.ngrinder.agent.controller.MonitorManagerController.java

/**
 * Get the target's monitored data by the given IP.
 *
 * @param ip target host IP//  w  ww  .  j a v a2 s  .c om
 * @return json message containing the target's monitoring data.
 */
@RequestMapping("/state")
@RestAPI
public HttpEntity<String> getRealTimeMonitorData(@RequestParam final String ip)
        throws InterruptedException, ExecutionException, TimeoutException {
    Future<SystemInfo> submit = Executors.newCachedThreadPool().submit(new Callable<SystemInfo>() {
        @Override
        public SystemInfo call() {
            return monitorInfoStore.getSystemInfo(ip, getConfig().getMonitorPort());
        }
    });
    SystemInfo systemInfo = checkNotNull(submit.get(2, TimeUnit.SECONDS), "Monitoring data is not available.");
    return toJsonHttpEntity(new SystemDataModel(systemInfo, "UNKNOWN"));
}

From source file:org.cryptomator.ui.CryptomatorModule.java

@Provides
@Singleton/*from w  w w  .  j a  v a  2 s  . co  m*/
ExecutorService provideExecutorService(DeferredCloser closer) {
    return closer.closeLater(Executors.newCachedThreadPool(), ExecutorService::shutdown).get()
            .orElseThrow(IllegalStateException::new);
}

From source file:com.dtstack.jlogstash.distributed.netty.server.NettyRev.java

public void startup() {
    try {/*  www.  j  ava 2  s.c o m*/
        bossExecutor = Executors.newCachedThreadPool();
        workerExecutor = Executors.newCachedThreadPool();
        bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(bossExecutor, workerExecutor));
        final NettyServerHandler nettyServerHandler = new NettyServerHandler();
        // ?????(Handler)
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder", new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, false, true,
                        ChannelBuffers.copiedBuffer(delimiter, Charset.forName(encoding))));
                pipeline.addLast("handler", nettyServerHandler);
                return pipeline;
            }
        });
        bootstrap.setOption("child.receiveBufferSize", receiveBufferSize);
        bootstrap.setOption("child.keepAlive", true);
        //            bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
        logger.warn("netty server start up success port:{}.", port);
    } catch (Exception e) {
        logger.error(e.getMessage());
        System.exit(1);
    }
}

From source file:pl.bristleback.server.bristle.engine.netty.NettyServerEngine.java

@Override
public void startServer() {
    log.info("Starting Netty engine (" + getClass().getName() + ") on port "
            + getEngineConfiguration().getPort());
    EngineConfig engineConfig = getEngineConfiguration();
    ChannelFactory nioChannelFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());
    ServerBootstrap bootstrap = new ServerBootstrap(nioChannelFactory);
    pipelineFactory.init(this);
    bootstrap.setPipelineFactory(pipelineFactory);
    serverChannel = bootstrap.bind(new InetSocketAddress(engineConfig.getPort()));
    log.info("Netty engine (" + getClass().getName() + ") on port " + getEngineConfiguration().getPort()
            + " has started.");
}