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.umn.msi.tropix.common.concurrent.impl.CachedSupport.java

@PostConstruct
public void init() {
    if (cache) {//w  w w .  ja  v  a  2  s . c o m
        if (cacheDuringInitialization) {
            setupCachingLoop();
        } else {
            // Avoid bug in spring by letting init() finish before setupCachingLoop needs to.
            Executors.newSingleThreadExecutor().execute(new Runnable() {
                public void run() {
                    setupCachingLoop();
                }
            });

        }
    }
}

From source file:com.astexample.Recognize.java

/**
 * Construct client connecting to Cloud Speech server at {@code host:port}.
 *///from  w  w w .  j  a  v  a2  s .c o  m
public Recognize(String host, int port, String file, int samplingRate) throws IOException {
    this.host = host;
    this.port = port;
    this.file = file;
    this.samplingRate = samplingRate;

    GoogleCredentials creds = GoogleCredentials.getApplicationDefault();
    creds = creds.createScoped(OAUTH2_SCOPES);
    channel = NettyChannelBuilder.forAddress(host, port).negotiationType(NegotiationType.TLS)
            .intercept(new ClientAuthInterceptor(creds, Executors.newSingleThreadExecutor())).build();
    stub = SpeechGrpc.newStub(channel);
    logger.info("Created stub for " + host + ":" + port);
}

From source file:com.astexample.RecognizeGoogleTest.java

/**
 * Construct client connecting to Cloud Speech server at {@code host:port}.
 *///from w  w  w  .  j a v a 2  s  .  c  o m
public RecognizeGoogleTest(String host, int port, String file, int samplingRate) throws IOException {
    this.host = host;
    this.port = port;
    this.file = file;
    this.samplingRate = samplingRate;

    GoogleCredentials creds = GoogleCredentials.getApplicationDefault();
    creds = creds.createScoped(OAUTH2_SCOPES);
    channel = NettyChannelBuilder.forAddress(host, port).negotiationType(NegotiationType.TLS)
            .intercept(new ClientAuthInterceptor(creds, Executors.newSingleThreadExecutor())).build();
    stub = SpeechGrpc.newStub(channel);
    logger.info("Created stub for " + host + ":" + port);
}

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

@Test
public void testSSL() throws InterruptedException {
    int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "3", "-ssl" },
            MixServer.getOptions());/*from   w  w w .java  2 s.  co  m*/
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);

    waitForState(server, ServerState.RUNNING);

    PredictionModel model = new DenseModel(16777216, false);
    model.configureClock();
    MixClient client = null;
    try {
        client = new MixClient(MixEventName.average, "testSSL", "localhost:" + port, true, 2, model);
        model.configureMix(client, false);

        final Random rand = new Random(43);
        for (int i = 0; i < 100000; i++) {
            Integer feature = Integer.valueOf(rand.nextInt(100));
            float weight = (float) rand.nextGaussian();
            model.set(feature, new WeightValue(weight));
        }

        Thread.sleep(5000L);

        long numMixed = model.getNumMixed();
        Assert.assertEquals("number of mix events: " + numMixed, numMixed, 0L);

        serverExec.shutdown();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.google.cloud.speech.grpc.demos.RecognizeClient.java

/**
 * Construct client connecting to Cloud Speech server at {@code host:port}.
 *//*from   w w  w. j  av  a2  s . co  m*/
public RecognizeClient(String host, int port, String file, int samplingRate) throws IOException {
    this.host = host;
    this.port = port;
    this.file = file;
    this.samplingRate = samplingRate;

    GoogleCredentials creds = GoogleCredentials.getApplicationDefault();
    creds = creds.createScoped(OAUTH2_SCOPES);
    channel = NettyChannelBuilder.forAddress(host, port).negotiationType(NegotiationType.TLS)
            .intercept(new ClientAuthInterceptor(creds, Executors.newSingleThreadExecutor())).build();
    stub = SpeechGrpc.newStub(channel);
    logger.info("Created stub for " + host + ":" + port);
}

From source file:com.codefollower.lealone.omid.tso.TSOTestBase.java

@BeforeClass
public static void setupBookkeeper() throws Exception {
    System.out.println("PATH : " + System.getProperty("java.library.path"));

    if (bkExecutor == null) {
        bkExecutor = Executors.newSingleThreadExecutor();
        Runnable bkTask = new Runnable() {
            public void run() {
                try {
                    Thread.currentThread().setName("BookKeeper");
                    String[] args = new String[1];
                    args[0] = "5";
                    LOG.info("Starting bk");
                    LocalBookKeeper.main(args);
                } catch (InterruptedException e) {
                    // go away quietly
                } catch (Exception e) {
                    LOG.error("Error starting local bk", e);
                }//w w  w .ja va 2 s  .com
            }
        };

        bkExecutor.execute(bkTask);
    }
}

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

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

    // streamsApiConfiguration = reconfigure(streamsApiConfiguration);
    provider = new DatasiftWebhookResource();
    kafkaWriter = new KafkaPersistWriter(streamsApiConfiguration.getKafka());
    kafkaReader = new KafkaPersistReader(streamsApiConfiguration.getKafka());
    writer = new ElasticsearchPersistWriter(streamsApiConfiguration.getElasticsearch());

    executor = Executors.newSingleThreadExecutor();

    executor.execute(new StreamsLocalRunner());

    Thread.sleep(10000);/*from ww  w.  j  av a2 s . c o  m*/

    environment.jersey().register(provider);

}

From source file:com.opengamma.bbg.replay.BloombergTickWriterTest.java

@Test
public void ticksWriting() throws Exception {
    ZonedDateTime startTime = ZonedDateTime.now(Clock.systemUTC());

    //run test for 5secs
    long runTime = 5000;
    ExecutorService writerExecutor = Executors.newSingleThreadExecutor();
    Future<?> writerFuture = writerExecutor.submit(_writer);

    //create ticks generators
    ExecutorService ticksGeneratorExec = Executors.newSingleThreadExecutor();
    Future<?> ticksGenFuture = ticksGeneratorExec.submit(_ticksGenerator);

    s_logger.info("Test running for {}ms to generate ticks", runTime);
    Thread.sleep(runTime);/*from  w w w. ja  v  a  2s.c o m*/

    //terminate ticks generation after 1mins
    _ticksGenerator.terminate();
    sendTerminateMessage();

    //test should fail if ticksGenerator throws an exception
    ticksGenFuture.get();
    ticksGeneratorExec.shutdown();
    ticksGeneratorExec.awaitTermination(1, TimeUnit.SECONDS);

    //test should fail if writer throws an exception
    writerFuture.get();
    writerExecutor.shutdown();
    writerExecutor.awaitTermination(1, TimeUnit.SECONDS);

    ZonedDateTime endTime = ZonedDateTime.now(Clock.systemUTC());

    //now lets replay generated allTicks.dat
    Set<String> buids = Sets.newHashSet(_ticker2buid.values());
    UnitTestTickReceiver receiver = new UnitTestTickReceiver();
    BloombergTicksReplayer player = new BloombergTicksReplayer(Mode.AS_FAST_AS_POSSIBLE,
            _rootDir.getAbsolutePath(), receiver, startTime, endTime, buids);
    player.start();
    while (player.isRunning()) {
        Thread.sleep(1000);
    }
    assertTrue(receiver.count() > 0);
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

public SqpConnectionImpl(ClientConfig config) {
    _logger = Logger.getGlobal();
    _messageEncoder = new JacksonMessageEncoder();
    _state = ConnectionState.Uninitialized;
    _config = config;//from w w w .java2s . c  o  m
    _cursorId = 0;
    _statementId = 0;
    _openServerResources = new HashMap<>();
    _autocommit = true;
    _lobManager = new LobManager(this);
    _sendingService = Executors.newSingleThreadExecutor(); // important that this only one thread to assure correct order
}

From source file:pl.bristleback.server.bristle.message.akka.SingleThreadMessageDispatcher.java

@Override
public void startDispatching() {
    if (dispatcherRunning) {
        throw new IllegalStateException("Dispatcher already running.");
    }/*from  ww w.  j  a  v  a 2 s.  co m*/
    log.info("Starting single threaded message dispatcher");
    ActorSystem system = ActorSystem.create("BristlebackSystem");
    sendMessageActor = system.actorOf(new Props(new UntypedActorFactory() {
        public UntypedActor create() {
            return new SendMessageActor(getServer());
        }
    }), "MessageDispatcherActor");
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    setDispatcherRunning(true);
    executorService.execute(new Dispatcher());
}