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:com.echopf.ECHOFile.java

/**
 * {@.en Gets a remote file data.}// w w w  .j a  v a 2 s . c  o m
 * {@.ja ??????}
 * @throws ECHOException 
 */
public byte[] getRemoteBytes() throws ECHOException {

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<byte[]> communicator = new Callable<byte[]>() {
        @Override
        public byte[] call() throws Exception {
            InputStream is = getRemoteInputStream();

            int nRead;
            byte[] data = new byte[16384];
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();

            return buffer.toByteArray();
        }
    };

    Future<byte[]> future = executor.submit(communicator);

    try {
        return future.get();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // ignore/reset
    } catch (ExecutionException e) {
        Throwable e2 = e.getCause();
        throw new ECHOException(e2);
    }

    return null;
}

From source file:com.mirth.connect.client.ui.components.ChannelTableTransferHandler.java

@Override
public boolean importData(TransferSupport support) {
    if (canImport(support)) {
        try {//from w ww .  j  a v  a 2 s  .  c o m
            if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                List<File> fileList = (List<File>) support.getTransferable()
                        .getTransferData(DataFlavor.javaFileListFlavor);
                final boolean showAlerts = (fileList.size() == 1);

                // Submit each import task to a single-threaded executor so they always import one at a time.
                Executor executor = Executors.newSingleThreadExecutor();

                for (final File file : fileList) {
                    if (FilenameUtils.isExtension(file.getName(), "xml")) {
                        executor.execute(new Runnable() {
                            @Override
                            public void run() {
                                importFile(file, showAlerts);
                            }
                        });
                    }
                }

                return true;
            } else if (support.isDataFlavorSupported(ChannelTableTransferable.CHANNEL_DATA_FLAVOR)) {
                List<Object> list = (List<Object>) support.getTransferable()
                        .getTransferData(ChannelTableTransferable.CHANNEL_DATA_FLAVOR);

                List<Channel> channels = new ArrayList<Channel>();
                for (Object obj : list) {
                    if (obj instanceof Channel) {
                        channels.add((Channel) obj);
                    } else {
                        return false;
                    }
                }

                if (support.getDropLocation() instanceof JTable.DropLocation) {
                    return moveChannels(channels, ((JTable.DropLocation) support.getDropLocation()).getRow());
                }
            }
        } catch (Exception e) {
            // Let it return false
        }
    }

    return false;
}

From source file:com.coveo.spillway.storage.AsyncLimitUsageStorage.java

public AsyncLimitUsageStorage(LimitUsageStorage wrappedLimitUsageStorage) {
    this.wrappedLimitUsageStorage = wrappedLimitUsageStorage;
    this.executorService = Executors.newSingleThreadExecutor();
    this.cache = new InMemoryStorage();
}

From source file:com.streamsets.pipeline.stage.executor.s3.TestAmazonS3Executor.java

@BeforeClass
public static void setUpClass() throws IOException, InterruptedException {
    File dir = new File(new File("target", UUID.randomUUID().toString()), "fakes3_root").getAbsoluteFile();
    Assert.assertTrue(dir.mkdirs());//  w  ww .ja v  a2  s. co m
    fakeS3Root = dir.getAbsolutePath();
    port = TestUtil.getFreePort();
    fakeS3 = new FakeS3(fakeS3Root, port);
    Assume.assumeTrue("Please install fakes3 in your system", fakeS3.fakes3Installed());
    //Start the fakes3 server
    executorService = Executors.newSingleThreadExecutor();
    executorService.submit(fakeS3);

    BasicAWSCredentials credentials = new BasicAWSCredentials("foo", "bar");
    s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials))
            .withEndpointConfiguration(
                    new AwsClientBuilder.EndpointConfiguration("http://localhost:" + port, null))
            .withPathStyleAccessEnabled(true).withChunkedEncodingDisabled(true) // FakeS3 does not correctly calculate checksums with chunked encoding enabled.
            .build();

    TestUtil.createBucket(s3client, BUCKET_NAME);
    TestUtil.createBucket(s3client, SECOND_BUCKET_NAME);
}

From source file:com.github.ljtfreitas.restify.http.spring.client.call.exec.DeferredResultEndpointCallExecutableFactory.java

public DeferredResultEndpointCallExecutableFactory(Long timeout) {
    this(timeout, Executors.newSingleThreadExecutor());
}

From source file:de.dfki.iui.mmds.scxml.engine.SCXMLEngineActivator.java

public static void postScxmlOnEntryEvent(final String id, final TransitionTarget state) {
    if (getEventAdmin() == null)
        return;/*from   w  w w .j a  v  a  2s .  c  o m*/
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override
        public void run() {
            getEventAdmin().postEvent(new SCXMLOnEntryEvent(id, state));
        }
    });
}

From source file:com.mirth.connect.connectors.jdbc.test.DatabaseDispatcherTests.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
    connection.setAutoCommit(true);//ww  w . j  ava  2  s. co  m

    // start a basic server
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override
        public void run() {
            server.run();
        }
    });

    while (ConfigurationController.getInstance().getStatus() != ConfigurationController.STATUS_OK) {
        Thread.sleep(100);
    }
}

From source file:org.apache.streams.elasticsearch.ElasticsearchPersistReader.java

@Override
public void startStream() {
    LOGGER.debug("startStream");
    executor = Executors.newSingleThreadExecutor();
    readerTask = executor.submit(new ElasticsearchPersistReaderTask(this, elasticsearchQuery));
}

From source file:com.netflix.suro.input.thrift.ThriftServer.java

@Override
public void start() throws TTransportException {
    msgProcessor.start();//from  www .  j  a v a 2s .  c  o m

    logger.info("Starting ThriftServer with config " + config);
    CustomServerSocket transport = new CustomServerSocket(config);
    port = transport.getPort();
    SuroServer.Processor processor = new SuroServer.Processor<MessageSetProcessor>(msgProcessor);

    THsHaServer.Args serverArgs = new THsHaServer.Args(transport);
    serverArgs.workerThreads(config.getThriftWorkerThreadNum());
    serverArgs.processor(processor);
    serverArgs.maxReadBufferBytes = config.getThriftMaxReadBufferBytes();

    executor = Executors.newSingleThreadExecutor();

    server = new THsHaServer(serverArgs);
    Future<?> serverStarted = executor.submit(new Runnable() {
        @Override
        public void run() {
            server.serve();
        }
    });
    try {
        serverStarted.get(config.getStartupTimeout(), TimeUnit.MILLISECONDS);
        if (server.isServing()) {
            logger.info("Server started on port:" + config.getPort());
        } else {
            throw new RuntimeException("ThriftServer didn't start up within: " + config.getStartupTimeout());
        }
    } catch (InterruptedException e) {
        // ignore this type of exception
    } catch (TimeoutException e) {
        if (server.isServing()) {
            logger.info("Server started on port:" + config.getPort());
        } else {
            logger.error("ThriftServer didn't start up within: " + config.getStartupTimeout());
            Throwables.propagate(e);
        }
    } catch (ExecutionException e) {
        logger.error("Exception on starting ThriftServer: " + e.getMessage(), e);
        Throwables.propagate(e);
    }
}

From source file:net.kmycode.javaspeechserver.cloud.StreamingRecognizeClient.java

public static ManagedChannel createChannel(String host, int port) throws IOException {
    //GoogleCredentials creds = GoogleCredentials.getApplicationDefault();
    GoogleCredentials creds = GoogleCredentials.fromStream(new FileInputStream(CREDENTIAL_PATH));
    creds = creds.createScoped(OAUTH2_SCOPES);
    ManagedChannel channel = ManagedChannelBuilder.forAddress(host, port)
            .intercept(new ClientAuthInterceptor(creds, Executors.newSingleThreadExecutor())).build();

    return channel;
}