Example usage for java.util.concurrent Executors newSingleThreadExecutor

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

Introduction

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

Prototype

public static ExecutorService newSingleThreadExecutor() 

Source Link

Document

Creates an Executor that uses a single worker thread operating off an unbounded queue.

Usage

From source file:org.jboss.additional.testsuite.jdkall.past.eap_6_4_x.clustering.cluster.web.ClusteredWebSimpleTestCase.java

private void abstractGracefulServe(URL baseURL1, boolean undeployOnly)
        throws IllegalStateException, IOException, InterruptedException, Exception {

    final DefaultHttpClient client = HttpClientUtils.relaxedCookieHttpClient();
    String url1 = baseURL1.toString() + SimpleServlet.URL;

    // Make sure a normal request will succeed
    HttpResponse response = client.execute(new HttpGet(url1));
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    response.getEntity().getContent().close();

    // Send a long request - in parallel
    String longRunningUrl = url1 + "?" + SimpleServlet.REQUEST_DURATION_PARAM + "=" + REQUEST_DURATION;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<HttpResponse> future = executor.submit(new RequestTask(client, longRunningUrl));

    // Make sure long request has started
    Thread.sleep(1000);//from  www .j a  v a 2s  .  c om

    if (undeployOnly) {
        // Undeploy the app only.
        undeploy(DEPLOYMENT_1);
    } else {
        // Shutdown server.
        stop(CONTAINER_1);
    }

    // Get result of long request
    // This request should succeed since it initiated before server shutdown
    try {
        response = future.get();
        Assert.assertEquals("Request should succeed since it initiated before undeply or shutdown.",
                HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        response.getEntity().getContent().close();
    } catch (ExecutionException e) {
        e.printStackTrace(System.err);
        Assert.fail(e.getCause().getMessage());
    }

    if (undeployOnly) {
        // If we are only undeploying, then subsequent requests should return 404.
        response = client.execute(new HttpGet(url1));
        Assert.assertEquals("If we are only undeploying, then subsequent requests should return 404.",
                HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
        response.getEntity().getContent().close();
    }

    // Cleanup after test.
    if (undeployOnly) {
        // Redeploy the app only.
        deploy(DEPLOYMENT_1);
    } else {
        // Startup server.
        start(CONTAINER_1);
    }
}

From source file:com.streamsets.pipeline.stage.origin.kafka.TestKafkaSource.java

@Test
public void testProduceJsonRecordsMultipleObjectsSingleRecord()
        throws StageException, IOException, InterruptedException {

    CountDownLatch startLatch = new CountDownLatch(1);
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(new ProducerRunnable(TOPIC3, SINGLE_PARTITION, producer, startLatch, DataType.JSON,
            StreamingJsonParser.Mode.MULTIPLE_OBJECTS, -1, null));

    KafkaConfigBean conf = new KafkaConfigBean();
    conf.metadataBrokerList = sdcKafkaTestUtil.getMetadataBrokerURI();
    conf.topic = TOPIC3;//from w  w w . ja v a 2 s.  c o  m
    conf.consumerGroup = CONSUMER_GROUP;
    conf.zookeeperConnect = zkConnect;
    conf.maxBatchSize = 9;
    conf.maxWaitTime = 5000;
    conf.kafkaConsumerConfigs = null;
    conf.produceSingleRecordPerMessage = true;
    conf.dataFormat = DataFormat.JSON;
    conf.dataFormatConfig.charset = "UTF-8";
    conf.dataFormatConfig.removeCtrlChars = false;
    conf.dataFormatConfig.jsonContent = JsonMode.MULTIPLE_OBJECTS;
    conf.dataFormatConfig.jsonMaxObjectLen = 4096;

    SourceRunner sourceRunner = new SourceRunner.Builder(StandaloneKafkaSource.class, createSource(conf))
            .addOutputLane("lane").build();

    sourceRunner.runInit();

    startLatch.countDown();
    List<Record> records = new ArrayList<>();
    StageRunner.Output output = getOutputAndRecords(sourceRunner, 9, "lane", records);

    shutDownExecutorService(executorService);

    String newOffset = output.getNewOffset();
    Assert.assertNull(newOffset);

    Assert.assertEquals(9, records.size());

    sourceRunner.runDestroy();
}

From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java

@Test
public void testNetworkTimeout() throws Exception {
    Connection conn = new MyProxy();

    try {//w  w w.  j av a 2  s .c o  m
        try {
            conn.getNetworkTimeout();
        } catch (SQLException e) {
            // Feature isn't supported by Derby
        }
        try {
            conn.setNetworkTimeout(Executors.newSingleThreadExecutor(), 1000);
        } catch (SQLException e) {
            // Feature isn't supported by Derby
        }
    } finally {
        JdbcUtil.closeQuietly(conn);
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpStreamResponse executeStreamWithTimeout(final HttpMethodBase HttpMethod, int timeoutMillis) {
    client.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false));
    ExecutorService service = Executors.newSingleThreadExecutor();

    Future<HttpStreamResponse> future = service.submit(new Callable<HttpStreamResponse>() {
        @Override/* w  ww. j  a  v a2  s  .c  om*/
        public HttpStreamResponse call() throws IOException {
            return executeStream(HttpMethod);
        }
    });

    try {
        return future.get(timeoutMillis, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        String uriInfo = "";
        try {
            uriInfo = " for " + HttpMethod.getURI();
        } catch (Exception ie) {
        }
        LOG.warn("Http connection thread was interrupted or has timed out" + uriInfo, e);
        return null;
    } finally {
        service.shutdownNow();
    }
}

From source file:com.all.rest.web.RestService.java

@PostConstruct
public void initialize() {
    restPeerUri = restConfig.getProperty(REST_PEER_URL_KEY);
    trackerServerUri = restConfig.getProperty(TRACKER_SERVER_URL_KEY);
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override//ww  w.j av  a  2  s.  c  o  m
        public void run() {
            verifyRestPeerHealth();
        }
    });
}

From source file:io.specto.hoverfly.junit.core.Hoverfly.java

private void cleanUp() {
    LOGGER.info("Destroying hoverfly process");

    if (startedProcess != null) {
        Process process = startedProcess.getProcess();
        process.destroy();//from w w  w .j  a  v  a2 s .c om

        // Some platforms terminate process asynchronously, eg. Windows, and cannot guarantee that synchronous file deletion
        // can acquire file lock
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<Integer> future = executorService.submit((Callable<Integer>) process::waitFor);
        try {
            future.get(5, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            LOGGER.warn("Timeout when waiting for hoverfly process to terminate.");
        }
        executorService.shutdownNow();
    }

    proxyConfigurer.restoreProxySystemProperties();
    // TODO: reset default SslContext?
    tempFileManager.purge();
}

From source file:com.all.rest.mc.RestMediaManager.java

@PostConstruct
public void init() {
    messEngine.addMessageListener(MessEngineConstants.REST_UPLOAD_TRACK_REQUEST_TYPE,
            new MessageListener<AllMessage<RestUploadRequest>>() {
                @Override/*from   w w  w  .j  ava2s .  c o  m*/
                public void onMessage(AllMessage<RestUploadRequest> message) {
                    String currentUser = restConfig.getUserId();
                    RestUploadRequest request = message.getBody();
                    if (currentUser == null || currentUser.equals(request.getRequester())) {
                        // ignoring auto requests.
                        return;
                    }
                    upload(request.getTrackId());

                }
            });
    Executors.newSingleThreadExecutor().execute(notifier);
}

From source file:com.o2d.pkayjava.editor.proxy.ProjectManager.java

public void importSpineAnimationsIntoProject(final Array<FileHandle> fileHandles,
        ProgressHandler progressHandler) {
    if (fileHandles == null) {
        return;//from w ww  .  jav  a 2s.co  m
    }
    handler = progressHandler;
    currentPercent = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(() -> {
        for (FileHandle handle : fileHandles) {
            File copiedFile = importExternalAnimationIntoProject(handle);
            if (copiedFile.getName().toLowerCase().endsWith(".atlas")) {
                ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
                resolutionManager.resizeSpineAnimationForAllResolutions(copiedFile, currentProjectInfoVO);
            } else if (copiedFile.getName().toLowerCase().endsWith(".scml")) {
                //resizeSpriterAnimationForAllResolutions(copiedFile, currentProjectInfoVO);
            }
        }

    });
    executor.execute(() -> {
        changePercentBy(100 - currentPercent);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        handler.progressComplete();
    });
    executor.shutdown();

}

From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java

/**
 * Performs a search of online recipes by keywords.
 * @param str The string of keywords we wish to search by.
 * @return ReturnCode.ERROR if anything goes wrong, ReturnCode.NO_RESULTS if
 * the search returned no results, ReturnCode.SUCCESS if the search was successful,
 * in which case the results are written to the database and the observing views
 * are notified, ReturnCode.BUSY if the server was busy or the operation took
 * longer than TIME_PERIOD seconds.//from  w  w w.jav a  2 s.  c  o  m
 */
public ReturnCode searchByKeywords(String str) throws ClientProtocolException, IOException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<ReturnCode> future = executor.submit(new SearchByKeywordsTask(str));
    ReturnCode ret = ReturnCode.ERROR;
    try {
        ret = future.get(TIMEOUT_PERIOD, TimeUnit.SECONDS);
    } catch (TimeoutException te) {
        logger.log(Level.SEVERE, "Search by Keywords operation timed out.");
        return ReturnCode.BUSY;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception during Search by Keywords operation.");
        return ReturnCode.ERROR;
    }
    /* Got here so the operation finished. */
    executor.shutdownNow();
    return ret;
}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * Create and connect mSocket.//from   w w  w .j  a  v  a 2s  .com
 *
 * @param task     task to be executed when connected to mSocket
 * @param download define if it is a download or upload test
 */
private void connectAndExecuteTask(final Runnable task, final boolean download) {

    // close mSocket before recreating it
    if (mSocket != null) {
        closeSocket();
    }
    try {
        /* create a basic mSocket connection */
        mSocket = new Socket();

        if (mSocketInterface.getSocketTimeout() != 0 && download) {
            mSocket.setSoTimeout(mSocketInterface.getSocketTimeout());
        }

        /* establish mSocket parameters */
        mSocket.setReuseAddress(true);

        mSocket.setKeepAlive(true);

        mSocket.connect(new InetSocketAddress(mHostname, mPort));

        if (mReadExecutorService == null || mReadExecutorService.isShutdown()) {
            mReadExecutorService = Executors.newSingleThreadExecutor();
        }

        mReadExecutorService.execute(new Runnable() {

            @Override
            public void run() {

                if (download) {
                    startSocketDownloadTask();
                } else {
                    startSocketUploadTask();
                }
                mSpeedTestMode = SpeedTestMode.NONE;
            }
        });

        if (mWriteExecutorService == null || mWriteExecutorService.isShutdown()) {
            mWriteExecutorService = Executors.newSingleThreadExecutor();
        }

        mWriteExecutorService.execute(new Runnable() {
            @Override
            public void run() {
                if (task != null) {
                    task.run();
                }
            }
        });

    } catch (IOException e) {
        if (!mErrorDispatched) {
            SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, download, e.getMessage());
        }
    }
}