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:org.mobicents.client.slee.resource.http.HttpClientResourceAdaptor.java

public void raActive() {
    activities = new ConcurrentHashMap<HttpClientActivityHandle, HttpClientActivity>();
    executorService = Executors.newCachedThreadPool();
    if (httpClientFactory != null) {
        httpclient = httpClientFactory.newHttpClient();
    } else {// w  ww.j  a  v  a 2  s.c  o m
        HttpParams params = new SyncBasicHttpParams();
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
        ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager(
                schemeRegistry);
        threadSafeClientConnManager.setMaxTotal(maxTotal);
        for (Entry<HttpRoute, Integer> entry : maxForRoutes.entrySet()) {
            if (tracer.isInfoEnabled()) {
                tracer.info(
                        String.format("Configuring MaxForRoute %s max %d", entry.getKey(), entry.getValue()));
            }
            threadSafeClientConnManager.setMaxForRoute(entry.getKey(), entry.getValue());
        }
        httpclient = new DefaultHttpClient(threadSafeClientConnManager, params);
    }
    isActive = true;
    if (tracer.isInfoEnabled()) {
        tracer.info(String.format("HttpClientResourceAdaptor=%s entity activated.",
                this.resourceAdaptorContext.getEntityName()));
    }
}

From source file:com.neudesic.azureservicebustest.asynchttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./* w  ww .j  a  va  2 s  . co m*/
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }

            request.addHeader("Accept", "*/*"); // SVG 5/8/2013 - intercept this to add for our API
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:com.revo.deployr.client.core.impl.RClientImpl.java

public RClientImpl(String serverurl, int concurrentCallLimit, boolean allowSelfSignedSSLCert)
        throws RClientException, RSecurityException {

    log.debug("Creating client connection: serverurl=" + serverurl + ", concurrentCallLimit="
            + concurrentCallLimit + ", allowSelfSignedSSLCert=" + allowSelfSignedSSLCert);

    this.serverurl = serverurl;

    // Create and initialize HTTP parameters
    HttpParams httpParams = new BasicHttpParams();
    // Set Infinite Connection and Socket Timeouts.
    HttpConnectionParams.setConnectionTimeout(httpParams, 0);
    HttpConnectionParams.setSoTimeout(httpParams, 0);
    ConnManagerParams.setMaxTotalConnections(httpParams, concurrentCallLimit);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(concurrentCallLimit));
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (allowSelfSignedSSLCert) {
        /*//from   ww  w.ja v a2s . c  om
         * Register scheme for "https" that bypasses
         * SSL cert trusted-origin verification check
         * which makes it possible to connect to a
         * DeployR server using a self-signed certificate.
         *
         * Recommended for prototyping and testing only,
         * not recommended for production environments.
         */
        TrustStrategy blindTrust = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] certificate, String authType) {
                return true;
            }
        };
        try {
            sslSocketFactory = new SSLSocketFactory(blindTrust, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", 8443, sslSocketFactory));
        } catch (GeneralSecurityException gsex) {
            String exMsg = "Self-signed SSL cert config failed, " + gsex.getMessage();
            log.debug(exMsg);
            throw new RSecurityException(exMsg, 0);
        }
    }

    // Create a HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpClient = new DefaultHttpClient(cm, httpParams);

    // Enable cookie handling by setting cookie policy on HttpClient.
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    log.debug("Created client connection: httpClient=" + httpClient);

    eService = Executors.newCachedThreadPool();

}

From source file:org.jboss.aerogear.sync.server.netty.DiffSyncHandlerTest.java

@Test
public void addDocumentWithContentConcurrent() throws Exception {
    final ExecutorService executorService = Executors.newCachedThreadPool();
    final int iterations = 100;
    final CountDownLatch await = new CountDownLatch(1);
    final CountDownLatch latch = new CountDownLatch(iterations);
    final String content = "You shall not pass!";
    final List<Future<PatchMessage<DiffMatchPatchEdit>>> futures = new ArrayList<Future<PatchMessage<DiffMatchPatchEdit>>>();
    final String client2Id = "client2";
    for (int i = 0; i < iterations; i++) {
        final String docId = UUID.randomUUID().toString();
        final ServerInMemoryDataStore<String, DiffMatchPatchEdit> dataStore = new ServerInMemoryDataStore<String, DiffMatchPatchEdit>();
        final EmbeddedChannel channel1 = embeddedChannel(dataStore);
        final EmbeddedChannel channel2 = embeddedChannel(dataStore);
        executorService.submit(new AddDocumentTask(channel1, docId, "client1", content, await, latch));
        final Future<PatchMessage<DiffMatchPatchEdit>> future = executorService
                .submit(new AddDocumentTask(channel2, docId, client2Id, content, await, latch));
        futures.add(future);//from www .  j  a v  a2  s .  co  m
    }
    await.countDown();
    latch.await();
    for (Future<PatchMessage<DiffMatchPatchEdit>> future : futures) {
        final PatchMessage<DiffMatchPatchEdit> patchMessage = future.get();
        assertThat(patchMessage.clientId(), equalTo(client2Id));
        assertThat(patchMessage.edits().size(), is(1));
        final DiffMatchPatchEdit edit = patchMessage.edits().peek();
        assertThat(edit.serverVersion(), is(1L));
        assertThat(edit.diff().diffs().get(0).operation(), is(Operation.UNCHANGED));
        assertThat(edit.diff().diffs().get(0).text(), equalTo(content));
    }
    executorService.shutdown();
}

From source file:de.huberlin.cuneiform.compiler.local.LocalDispatcher.java

protected Set<JsonReportEntry> dispatch(Invocation invocation)
        throws IOException, InterruptedException, NotDerivableException, JSONException {

    File scriptFile;/*  w ww .  j a  v  a2s .c o m*/
    Process process;
    int exitValue;
    Set<JsonReportEntry> report;
    String line;
    String[] arg;
    String value;
    int i;
    StringBuffer buf;
    File location;
    File reportFile;
    StreamConsumer stdoutConsumer, errConsumer;
    ExecutorService executor;
    String signature;
    Path srcPath, destPath;
    File successMarker;

    if (invocation == null)
        throw new NullPointerException("Invocation must not be null.");

    if (!invocation.isReady())
        throw new RuntimeException("Cannot dispatch invocation that is not ready.");

    location = new File(buildDir.getAbsolutePath() + "/" + invocation.getSignature());
    successMarker = new File(location.getAbsolutePath() + "/" + SUCCESS_FILENAME);
    reportFile = new File(location.getAbsolutePath() + "/" + Invocation.REPORT_FILENAME);

    if (!successMarker.exists()) {

        if (location.exists())
            FileUtils.deleteDirectory(location);

        if (!location.mkdirs())
            throw new IOException("Could not create invocation location.");

        scriptFile = new File(location.getAbsolutePath() + "/" + SCRIPT_FILENAME);

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(scriptFile, false))) {

            // write away script
            writer.write(invocation.toScript());

        }

        scriptFile.setExecutable(true);

        for (String filename : invocation.getStageInList()) {

            if (filename.charAt(0) != '/' && filename.indexOf('_') >= 0) {

                signature = filename.substring(0, filename.indexOf('_'));

                srcPath = FileSystems.getDefault()
                        .getPath(buildDir.getAbsolutePath() + "/" + signature + "/" + filename);
                destPath = FileSystems.getDefault()
                        .getPath(buildDir.getAbsolutePath() + "/" + invocation.getSignature() + "/" + filename);
                Files.createSymbolicLink(destPath, srcPath);
            }
        }

        arg = new String[] { "/usr/bin/time", "-a", "-o",
                location.getAbsolutePath() + "/" + Invocation.REPORT_FILENAME, "-f",
                "{" + JsonReportEntry.ATT_TIMESTAMP + ":" + System.currentTimeMillis() + ","
                        + JsonReportEntry.ATT_RUNID + ":\"" + invocation.getDagId() + "\","
                        + JsonReportEntry.ATT_TASKID + ":" + invocation.getTaskNodeId() + ","
                        + JsonReportEntry.ATT_TASKNAME + ":\"" + invocation.getTaskName() + "\","
                        + JsonReportEntry.ATT_LANG + ":\"" + invocation.getLangLabel() + "\","
                        + JsonReportEntry.ATT_INVOCID + ":" + invocation.getSignature() + ","
                        + JsonReportEntry.ATT_KEY + ":\"" + JsonReportEntry.KEY_INVOC_TIME + "\","
                        + JsonReportEntry.ATT_VALUE + ":" + "{\"realTime\":%e,\"userTime\":%U,\"sysTime\":%S,"
                        + "\"maxResidentSetSize\":%M,\"avgResidentSetSize\":%t,"
                        + "\"avgDataSize\":%D,\"avgStackSize\":%p,\"avgTextSize\":%X,"
                        + "\"nMajPageFault\":%F,\"nMinPageFault\":%R,"
                        + "\"nSwapOutMainMem\":%W,\"nForcedContextSwitch\":%c,"
                        + "\"nWaitContextSwitch\":%w,\"nIoRead\":%I,\"nIoWrite\":%O,"
                        + "\"nSocketRead\":%r,\"nSocketWrite\":%s,\"nSignal\":%k}}",
                scriptFile.getAbsolutePath() };

        // run script
        process = Runtime.getRuntime().exec(arg, null, location);

        executor = Executors.newCachedThreadPool();

        stdoutConsumer = new StreamConsumer(process.getInputStream());
        executor.execute(stdoutConsumer);

        errConsumer = new StreamConsumer(process.getErrorStream());
        executor.execute(errConsumer);

        executor.shutdown();

        exitValue = process.waitFor();
        if (!executor.awaitTermination(4, TimeUnit.SECONDS))
            throw new RuntimeException("Consumer threads did not finish orderly.");

        try (BufferedWriter reportWriter = new BufferedWriter(new FileWriter(reportFile, true))) {

            if (exitValue != 0) {

                System.err.println("[script]");

                try (BufferedReader reader = new BufferedReader(new StringReader(invocation.toScript()))) {

                    i = 0;
                    while ((line = reader.readLine()) != null)
                        System.err.println(String.format("%02d  %s", ++i, line));
                }

                System.err.println("[out]");
                try (BufferedReader reader = new BufferedReader(
                        new StringReader(stdoutConsumer.getContent()))) {

                    while ((line = reader.readLine()) != null)
                        System.err.println(line);
                }

                System.err.println("[err]");
                try (BufferedReader reader = new BufferedReader(new StringReader(errConsumer.getContent()))) {

                    while ((line = reader.readLine()) != null)
                        System.err.println(line);
                }

                System.err.println("[end]");

                throw new RuntimeException("Invocation of task '" + invocation.getTaskName()
                        + "' with signature " + invocation.getSignature()
                        + " terminated with non-zero exit value. Exit value was " + exitValue + ".");
            }

            try (BufferedReader reader = new BufferedReader(new StringReader(stdoutConsumer.getContent()))) {

                buf = new StringBuffer();
                while ((line = reader.readLine()) != null)
                    buf.append(line.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"")).append('\n');

                value = buf.toString();
                if (!value.isEmpty())

                    reportWriter.write(new JsonReportEntry(invocation, JsonReportEntry.KEY_INVOC_STDOUT, value)
                            .toString());
            }
            try (BufferedReader reader = new BufferedReader(new StringReader(errConsumer.getContent()))) {

                buf = new StringBuffer();
                while ((line = reader.readLine()) != null)
                    buf.append(line.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"")).append('\n');

                value = buf.toString();
                if (!value.isEmpty())

                    reportWriter.write(new JsonReportEntry(invocation, JsonReportEntry.KEY_INVOC_STDERR, value)
                            .toString());
            }

        }
    }

    // gather report
    report = new HashSet<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(reportFile))) {

        while ((line = reader.readLine()) != null) {

            line = line.trim();

            if (line.isEmpty())
                continue;

            report.add(new JsonReportEntry(line));
        }

    }

    invocation.evalReport(report);

    if (!successMarker.exists())
        if (!successMarker.createNewFile())
            throw new IOException("Could not create success marker.");

    return report;
}

From source file:hws.core.ExecutorThread.java

public void run(String[] args) throws IOException, ClassNotFoundException, InstantiationException,
        IllegalAccessException, ParseException {
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("app-id").withDescription("String of the Application Id")
            .hasArg().withArgName("AppId").create("aid"));
    options.addOption(OptionBuilder.withLongOpt("container-id").withDescription("String of the Container Id")
            .hasArg().withArgName("ContainerId").create("cid"));
    options.addOption(OptionBuilder.withLongOpt("load").withDescription("load module instance").hasArg()
            .withArgName("Json-Base64").create());
    options.addOption(OptionBuilder.withLongOpt("zk-servers").withDescription("List of the ZooKeeper servers")
            .hasArgs().withArgName("zkAddrs").create("zks"));
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    String appIdStr = null;// www  .  j a v a 2  s  . co  m
    String containerIdStr = null;
    String instanceInfoBase64 = null;
    String instanceInfoJson = null;
    InstanceInfo instanceInfo = null;

    if (cmd.hasOption("aid")) {
        appIdStr = cmd.getOptionValue("aid");
    }
    if (cmd.hasOption("cid")) {
        containerIdStr = cmd.getOptionValue("cid");
    }
    String zksArgs = "";
    String[] zkServers = null;
    if (cmd.hasOption("zks")) {
        zksArgs = "-zks";
        zkServers = cmd.getOptionValues("zks");
        for (String zks : zkServers) {
            zksArgs += " " + zks;
        }
    }

    //Logger setup
    Configuration conf = new Configuration();
    FileSystem fileSystem = FileSystem.get(conf);
    FSDataOutputStream writer = fileSystem
            .create(new Path("hdfs:///hws/apps/" + appIdStr + "/logs/" + containerIdStr + ".log"));
    Logger.addOutputStream(writer);

    Logger.info("Processing Instance");

    if (cmd.hasOption("load")) {
        instanceInfoBase64 = cmd.getOptionValue("load");
        instanceInfoJson = StringUtils.newStringUtf8(Base64.decodeBase64(instanceInfoBase64));
        instanceInfo = Json.loads(instanceInfoJson, InstanceInfo.class);
    }

    Logger.info("Instance info: " + instanceInfoJson);

    this.latch = new CountDownLatch(instanceInfo.inputChannels().keySet().size());
    Logger.info("Latch Countdowns: " + instanceInfo.inputChannels().keySet().size());

    ZkClient zk = new ZkClient(zkServers[0]); //TODO select a ZooKeeper server

    Logger.info("Load Instance " + instanceInfo.instanceId());
    loadInstance(instanceInfo, zk, "/hadoop-watershed/" + appIdStr + "/");

    IZkChildListener producersHaltedListener = createProducersHaltedListener();
    String znode = "/hadoop-watershed/" + appIdStr + "/" + instanceInfo.filterInfo().name() + "/halted";
    Logger.info("halting znode: " + znode);
    zk.subscribeChildChanges(znode, producersHaltedListener);

    ExecutorService serverExecutor = Executors.newCachedThreadPool();

    //wait for a start command from the ApplicationMaster via ZooKeeper
    znode = "/hadoop-watershed/" + appIdStr + "/" + instanceInfo.filterInfo().name() + "/start";
    Logger.info("starting znode: " + znode);
    zk.waitUntilExists(znode, TimeUnit.MILLISECONDS, 250);
    Logger.info("Exists: " + zk.exists(znode));
    /*
    while(!zk.waitUntilExists(znode,TimeUnit.MILLISECONDS, 500)){
       //out.println("TIMEOUT waiting for start znode: "+znode);
       //out.flush();
    }*/
    //start and execute this instance
    Logger.info("Starting Instance");
    startExecutors(serverExecutor);
    Logger.info("Instance STARTED");

    Logger.info("Waiting TERMINATION");

    try {
        this.latch.await(); //await the input threads to finish
    } catch (InterruptedException e) {
        // handle
        Logger.severe("Waiting ERROR: " + e.getMessage());
    }

    Logger.info("Finishing Instance");
    finishExecutors();
    Logger.info("FINISHED Instance " + instanceInfo.instanceId());
    String finishZnode = "/hadoop-watershed/" + appIdStr + "/" + instanceInfo.filterInfo().name() + "/finish/"
            + instanceInfo.instanceId();
    zk.createPersistent(finishZnode, "");
}

From source file:com.linkedin.pinot.integration.tests.HybridClusterScanComparisonIntegrationTest.java

@Override
@BeforeClass/*w w  w .  j a  v a  2  s.c  o m*/
public void setUp() throws Exception {
    //Clean up
    ensureDirectoryExistsAndIsEmpty(_tmpDir);
    ensureDirectoryExistsAndIsEmpty(_segmentDir);
    ensureDirectoryExistsAndIsEmpty(_offlineSegmentDir);
    ensureDirectoryExistsAndIsEmpty(_realtimeSegmentDir);
    ensureDirectoryExistsAndIsEmpty(_offlineTarDir);
    ensureDirectoryExistsAndIsEmpty(_realtimeTarDir);
    ensureDirectoryExistsAndIsEmpty(_unpackedSegments);

    // Start Zk, Kafka and Pinot
    startHybridCluster();

    extractAvroIfNeeded();

    int avroFileCount = getAvroFileCount();
    Preconditions.checkArgument(3 <= avroFileCount, "Need at least three Avro files for this test");

    setSegmentCount(avroFileCount);
    setOfflineSegmentCount(2);
    setRealtimeSegmentCount(avroFileCount - 1);

    final List<File> avroFiles = getAllAvroFiles();

    _schemaFile = getSchemaFile();
    _schema = Schema.fromFile(_schemaFile);

    // Create Pinot table
    setUpTable("mytable", getTimeColumnName(), getTimeColumnType(), KafkaStarterUtils.DEFAULT_ZK_STR,
            KAFKA_TOPIC, _schemaFile, avroFiles.get(0), getSortedColumn(), invertedIndexColumns);

    final List<File> offlineAvroFiles = getOfflineAvroFiles(avroFiles);
    final List<File> realtimeAvroFiles = getRealtimeAvroFiles(avroFiles);

    // Create segments from Avro data
    ExecutorService executor;
    if (_createSegmentsInParallel) {
        executor = Executors.newCachedThreadPool();
    } else {
        executor = Executors.newSingleThreadExecutor();

    }
    Future<Map<File, File>> offlineAvroToSegmentMapFuture = buildSegmentsFromAvro(offlineAvroFiles, executor, 0,
            _offlineSegmentDir, _offlineTarDir, "mytable", false, _schema);
    Future<Map<File, File>> realtimeAvroToSegmentMapFuture = buildSegmentsFromAvro(realtimeAvroFiles, executor,
            0, _realtimeSegmentDir, _realtimeTarDir, "mytable", false, _schema);

    // Initialize query generator
    setupQueryGenerator(avroFiles, executor);

    // Redeem futures
    _offlineAvroToSegmentMap = offlineAvroToSegmentMapFuture.get();
    _realtimeAvroToSegmentMap = realtimeAvroToSegmentMapFuture.get();

    LOGGER.info("Offline avro to segment map: {}", _offlineAvroToSegmentMap);
    LOGGER.info("Realtime avro to segment map: {}", _realtimeAvroToSegmentMap);

    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.MINUTES);

    // Set up a Helix spectator to count the number of segments that are uploaded and unlock the latch once 12 segments are online
    final CountDownLatch latch = setupSegmentCountCountDownLatch("mytable", getOfflineSegmentCount());

    // Upload the offline segments
    int i = 0;
    for (String segmentName : _offlineTarDir.list()) {
        i++;
        LOGGER.info("Uploading segment {} : {}", i, segmentName);
        File file = new File(_offlineTarDir, segmentName);
        FileUploadUtils.sendSegmentFile("localhost", "8998", segmentName, new FileInputStream(file),
                file.length());
    }

    // Wait for all offline segments to be online
    latch.await();

    _compareStatusFileWriter = getLogWriter();
    _scanRspFileWriter = getScanRspRecordFileWriter();
    _compareStatusFileWriter.write("Start time:" + System.currentTimeMillis() + "\n");
    _compareStatusFileWriter.flush();
    startTimeMs = System.currentTimeMillis();
    LOGGER.info("Setup completed");
}

From source file:hivemall.mix.server.MixServerTest.java

@Test
public void test2ClientsZeroOneDenseModel() throws InterruptedException {
    final int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "30" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);/*from w w w.j  a v  a  2s .c o  m*/

    waitForState(server, ServerState.RUNNING);

    final ExecutorService clientsExec = Executors.newCachedThreadPool();
    for (int i = 0; i < 2; i++) {
        clientsExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    invokeClient01("test2ClientsZeroOne", port, true, false);
                } catch (InterruptedException e) {
                    Assert.fail(e.getMessage());
                }
            }
        });
    }
    clientsExec.awaitTermination(30, TimeUnit.SECONDS);
    clientsExec.shutdown();
    serverExec.shutdown();
}

From source file:org.inaetics.pubsub.impl.discovery.etcd.EtcdDiscoveryManager.java

protected final void start() {
    myBundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
    localFrameworkUUID = Utils.getFrameworkUUID(myBundleContext);

    System.out.println("STARTED " + this.getClass().getName());

    etcdWrapper = new EtcdWrapper(etcdUrl);
    executor = Executors.newCachedThreadPool();
    refresher = new TTLRefresher(etcdUrl);
    refresher.start();/*from w w  w.j a  va 2 s  .  c  o  m*/
    responseListener = new ResponseListener();
    stopped = false;

    executor.execute(new Runnable() {
        @Override
        public void run() {
            initDiscovery();
        }
    });
}

From source file:org.geoserver.wps.executor.WPSExecutionManager.java

@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ContextRefreshedEvent) {
        if (storedResponseWriters == null) {
            storedResponseWriters = Executors.newCachedThreadPool();
        } else if (event instanceof ContextClosedEvent) {
            storedResponseWriters.shutdownNow();
        }//  w  ww. j a v  a2  s. c  om
    }
}