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:edu.lternet.pasta.dml.util.DocumentDownloadUtil.java

public InputStream downloadDocument(final String id, final EcogridEndPointInterface endpoint) throws Exception {

    init();//from w w w  .  j ava 2  s .  co m

    log.debug("starting the download");

    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(new Runnable() {
        public void run() {
            long startTime = System.currentTimeMillis();

            try {
                if (endpoint instanceof AuthenticatedEcogridEndPointInterface) {
                    AuthenticatedQueryServiceGetToStreamClient authenticatedEcogridClient = new AuthenticatedQueryServiceGetToStreamClient(
                            new URL(((AuthenticatedEcogridEndPointInterface) endpoint)
                                    .getMetacatAuthenticatedEcogridEndPoint()));
                    authenticatedEcogridClient.get(id,
                            ((AuthenticatedEcogridEndPointInterface) endpoint).getSessionId(), outputStream);
                } else {
                    QueryServiceGetToStreamClient ecogridClient = new QueryServiceGetToStreamClient(
                            new URL(endpoint.getMetacatEcogridEndPoint()));
                    ecogridClient.get(id, outputStream);
                }
                outputStream.close();

                long endTime = System.currentTimeMillis();
                log.debug((endTime - startTime) + " ms to download document data");

                log.debug("Done downloading id=" + id);

            } catch (Exception e) {
                log.error("Error getting document from ecogrid: " + e.getMessage());
                e.printStackTrace();
            }

        }
    });

    //wait for the download to complete
    service.shutdown();
    service.awaitTermination(0, TimeUnit.SECONDS);

    log.debug("done with the download");

    return inputStream;

}

From source file:com.github.brandtg.switchboard.FileLogAggregator.java

/**
 * An agent that aggregates logs from multiple sources and multiplexes them.
 *
 * @param sources//from  ww  w .  j  a v a 2s.  c o m
 *  A set of source switchboard servers from which to pull logs
 * @param separator
 *  The line delimiter (after this is reached, lines will be output to outputStream)
 * @param outputStream
 *  OutputStream to which all multiplexed logs are piped
 */
public FileLogAggregator(Set<InetSocketAddress> sources, char separator, OutputStream outputStream)
        throws IOException {
    this.separator = separator;
    this.outputStream = outputStream;
    this.isShutdown = new AtomicBoolean(true);
    this.eventExecutors = new NioEventLoopGroup();
    this.logReceivers = new HashMap<>();
    this.inputStreams = new HashMap<>();
    this.listener = new Object();
    this.muxExecutor = Executors.newSingleThreadExecutor();
    this.stringBuffers = new HashMap<>();

    for (InetSocketAddress source : sources) {
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);
        LogReceiver logReceiver = new LogReceiver(new InetSocketAddress(0), eventExecutors, pos);
        logReceiver.registerListener(listener);
        logReceivers.put(source, logReceiver);
        inputStreams.put(source, pis);
        stringBuffers.put(source, new StringBuffer());
    }
}

From source file:edu.lternet.pasta.dml.download.DocumentHandler.java

public InputStream downloadDocument() throws Exception {

    log.info("starting the download");

    boolean success = true;

    final String id = docId;
    final EcogridEndPointInterface endpoint = ecogridEndPointInterface;

    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(new Runnable() {
        public void run() {
            long startTime = System.currentTimeMillis();

            //get from the ecogrid
            try {
                if (ecogridEndPointInterface instanceof AuthenticatedEcogridEndPointInterface) {
                    AuthenticatedQueryServiceGetToStreamClient authenticatedEcogridClient = new AuthenticatedQueryServiceGetToStreamClient(
                            new URL(((AuthenticatedEcogridEndPointInterface) endpoint)
                                    .getMetacatAuthenticatedEcogridEndPoint()));
                    authenticatedEcogridClient.get(id,
                            ((AuthenticatedEcogridEndPointInterface) endpoint).getSessionId(), outputStream);
                } else {
                    QueryServiceGetToStreamClient ecogridClient = new QueryServiceGetToStreamClient(
                            new URL(endpoint.getMetacatEcogridEndPoint()));
                    ecogridClient.get(id, outputStream);
                }/*  w  w w. j  a v  a2s. co  m*/
                outputStream.close();
                long endTime = System.currentTimeMillis();
                log.debug((endTime - startTime) + " ms to download: " + docId);
                log.debug("Done downloading id=" + id);

            } catch (Exception e) {
                log.error("Error getting document from ecogrid: " + e.getMessage());
                e.printStackTrace();
            }

        }
    });

    //wait for the download to complete
    service.shutdown();
    service.awaitTermination(0, TimeUnit.SECONDS);

    return inputStream;
}

From source file:org.sample.asyncserver.MyResource.java

@GET
public void getList(@Suspended final AsyncResponse ar) {
    ar.setTimeoutHandler(new TimeoutHandler() {

        @Override//from   w w w.jav a 2  s .  c o  m
        public void handleTimeout(AsyncResponse ar) {
            ar.resume("Operation timed out");
        }
    });
    ar.setTimeout(4000, TimeUnit.MILLISECONDS);

    ar.register(new MyCompletionCallback());
    ar.register(new MyConnectionCallback());

    Executors.newSingleThreadExecutor().submit(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(3000);
                ar.resume(response[0]);
            } catch (InterruptedException ex) {

            }
        }

    });
}

From source file:com.meltmedia.cadmium.core.worker.CoordinatedWorkerImpl.java

public CoordinatedWorkerImpl() {
    pool = Executors.newSingleThreadExecutor();
    listener = this;
}

From source file:org.apache.streams.datasift.example.StreamsApiApplication.java

@Override
public void run(StreamsApiConfiguration configuration, Environment environment) throws Exception {

    this.configuration = configuration;

    provider = new DatasiftWebhookResource();

    executor = Executors.newSingleThreadExecutor();

    executor.execute(new StreamsLocalRunner());

    Thread.sleep(10000);//from ww  w .j a  va2s  .  c  o m

    environment.jersey().register(provider);

}

From source file:pzalejko.iot.hardware.home.core.app.Application.java

/**
 * Starts all services.//ww  w . j  av a  2  s  .  c  o  m
 * <p>
 * NOTE: When this method is done then the application can be closed.
 *
 * @throws ExecutionException if a task cannot be started.
 * @throws InterruptedException if a task has been interrupted.
 */
public void start() throws ExecutionException, InterruptedException {
    LOG.debug(LogMessages.STARTING_APPLICATION);

    taskExecutor.executeRepeatable(temperatureTask, temperatureTask.getReadFrequency());
    taskExecutor.execute(remoteLedControlTask);
    taskExecutor.execute(ledAlertTask);

    final ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(shutDownTask).get();
}

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

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

From source file:biz.fstechnology.micro.server.jms.AbstractJmsService.java

/**
 * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
 *///from   w  w w  .  j ava 2  s  .com
@Override
public void onMessage(Message message) {
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        if (((ObjectMessage) message).getObject() instanceof Result) {
            // no op
            return;
        }
        Request<?> request = (Request<?>) ((ObjectMessage) message).getObject(); // cast hell...
        Future<Request<?>> preProcessFuture = executor.submit(() -> onPreProcessRequest(request));

        Future<Result<?>> resultFuture = executor.submit(() -> processRequest(preProcessFuture.get()));

        Future<Result<?>> postProcessFuture = executor
                .submit(() -> onPostProcessRequest(request, resultFuture.get()));
        executor.shutdown();

        Result<?> result = postProcessFuture.get();

        ResponseMessageCreator messageCreator = new ResponseMessageCreator();
        messageCreator.setContents(result);
        messageCreator.setRequestId(message.getJMSCorrelationID());

        replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session));

    } catch (JMSException | InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Result<Object> result = new Result<>(e);
        try {
            ResponseMessageCreator messageCreator = new ResponseMessageCreator();
            messageCreator.setContents(result);
            messageCreator.setRequestId(message.getJMSCorrelationID());

            replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session));
        } catch (JmsException | JMSException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:com.google.code.guice.repository.testing.junit.general.UserRepositoryTest.java

@Test
public void testRepo() throws Exception {
    userRepository.deleteAll();//w ww. j  a v  a  2  s  .c  o  m
    userRepository.someCustomMethod(new User("one", "two", 42));

    userRepository.deleteInactiveUsers();
    userRepository.deleteOtherUsers();

    userRepository.deleteAll();
    assertEquals("Invalid repository size", 0, userRepository.count());

    userRepository.save(new User("john", "smith", 42));
    userRepository.save(new User("alex", "johns", 33));
    userRepository.save(new User("sam", "brown", 22));
    assertEquals("Invalid repository size", 3, userRepository.count());

    assertNotNull("User not found", userRepository.findUserByName("john"));

    Page<User> users = userRepository.findAll(new PageRequest(0, 100));
    assertEquals("Invalid requested page size", 3, users.getNumberOfElements());

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.invokeAll(Arrays.asList(Executors.callable(new Runnable() {
        @Override
        public void run() {
            try {
                logger.info("Start concurrent thread");
                UserRepository anotherRepo = userRepository;
                logger.info("count");
                assertEquals("Invalid repository size", 3, anotherRepo.count());
                logger.info("save");
                anotherRepo.save(new User(UUID.randomUUID().toString(), UUID.randomUUID().toString(), 10));
                assertEquals("Invalid repository size", 4, anotherRepo.count());
                logger.info("Stored 4");
            } catch (Exception e) {
                logger.error("Error", e);
            }
        }
    })));

    logger.info("After");
    assertEquals("Invalid repository size", 4, userRepository.count());
    userRepository.deleteAll();
    assertEquals("Invalid repository size", 0, userRepository.count());

    userRepository.someCustomMethod(new User("john", "smith", 42));
}