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:no.ntnu.idi.socialhitchhiking.map.GeoHelper.java

/**
 * Retrieves a {@link List} of addresses that match the given {@link GeoPoint}. 
 * The first element in the list has the best match (but is not guaranteed to be correct). <br><br>
 * /*from w w  w . j  a v  a2 s. c  o m*/
 * This method tries to use the {@link Geocoder} to transform a (latitude, longitude) 
 * coordinate into addresses, and if this fails (witch it most likely will under emulation), it 
 * tries to use a method from the {@link GeoHelper}-class.
 * 
 * @param location The location that is transformed into a list of addresses
 * @param maxResults The maximum number of addresses to retrieve (should be small).
 * @param maxAddressLines The maximum number of lines in the addresses. This should be high if you want a complete address! If it is smaller than the total number of lines in the address, it cuts off the last part...) 
 * @return Returns the {@link List} of addresses (as {@link String}s).
 */
public static List<String> getAddressesAtPoint(final GeoPoint location, final int maxResults,
        int maxAddressLines) {
    List<String> addressList = new ArrayList<String>();
    List<Address> possibleAddresses = new ArrayList<Address>();
    Address address = new Address(Locale.getDefault());
    String addressString = "Could not find the address...";
    ExecutorService executor = Executors.newSingleThreadExecutor();

    Callable<List<Address>> callable = new Callable<List<Address>>() {
        @Override
        public List<Address> call() throws IOException {
            return fancyGeocoder.getFromLocation(location.getLatitudeE6() / 1E6,
                    location.getLongitudeE6() / 1E6, maxResults);
        }
    };
    Future<List<Address>> future = executor.submit(callable);
    try {
        possibleAddresses = future.get();
    } catch (InterruptedException e1) {
        possibleAddresses = GeoHelper.getAddressesFromLocation(location.getLatitudeE6() / 1E6,
                location.getLongitudeE6() / 1E6, maxResults);
    } catch (ExecutionException e1) {
        possibleAddresses = GeoHelper.getAddressesFromLocation(location.getLatitudeE6() / 1E6,
                location.getLongitudeE6() / 1E6, maxResults);
    }
    executor.shutdown();

    if (possibleAddresses.size() > 0) {
        for (int i = 0; i < possibleAddresses.size(); i++) {
            addressString = "";
            address = possibleAddresses.get(i);
            for (int j = 0; j <= address.getMaxAddressLineIndex() && j <= maxAddressLines; j++) {
                addressString += address.getAddressLine(j);
                addressString += "\n";
            }
            addressList.add(addressString.trim());
        }
    }
    return addressList;
}

From source file:at.wada811.android.library.demos.concurrent.ExecutorActivity.java

/**
 * {@link Executors#newSingleThreadExecutor} ?
 * //from   w w w  . j  a  v a  2 s. com
 * <p>
 * SingleThread ???????????????
 * </p>
 */
public void newSingleThreadExecutorTest() {
    LogUtils.d();
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(new ExecutorRunnable("A", 1));
    executorService.submit(new ExecutorRunnable("B", 1));
    executorService.submit(new ExecutorRunnable("C", 1));
    executorService.submit(new ExecutorRunnable("D", 1));
}

From source file:com.mirth.connect.server.controllers.tests.TestUtils.java

public static void startMirthServer(int sleepMillis) throws InterruptedException {
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override//  ww  w . j  a va  2  s. com
        public void run() {
            new Mirth().run();
        }
    });

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

From source file:com.amazonaws.services.dynamodbv2.streamsadapter.functionals.FunctionalTestBase.java

protected void startKCLWorker(KinesisClientLibConfiguration workerConfig) {

    recordProcessorFactory = new TestRecordProcessorFactory(dynamoDBClient, destTable);

    LOG.info("Creating worker for stream: " + streamId);
    worker = StreamsWorkerFactory.createDynamoDbStreamsWorker(recordProcessorFactory, workerConfig,
            adapterClient, dynamoDBClient, new NullMetricsFactory(), Executors.newCachedThreadPool());

    LOG.info("Starting worker...");
    workerThread = Executors.newSingleThreadExecutor();
    workerThread.submit(worker);/*from  ww w  .j a va  2 s. c  om*/

    workerThread.shutdown(); //This will wait till the KCL worker exits
}

From source file:com.canoo.dolphin.client.impl.ClientContextImpl.java

@Override
public synchronized CompletableFuture<Void> disconnect() {
    checkForInitializedState();//  w  w  w  .  ja v a  2 s. c o  m
    state = State.DESTROYING;
    clientDolphin.stopPushListening();
    final CompletableFuture<Void> result = new CompletableFuture<>();

    Executors.newSingleThreadExecutor().execute(() -> {
        state = State.DESTROYED;
        dolphinCommandHandler.invokeDolphinCommand(PlatformConstants.DESTROY_CONTEXT_COMMAND_NAME)
                .handle((v, t) -> {
                    if (t != null) {
                        result.completeExceptionally(new DolphinRemotingException("Can't disconnect", t));
                    } else {
                        result.complete(null);
                    }
                    return null;
                });
        //TODO: Stop communication in client connector
    });

    return result;
}

From source file:com.yahoo.yqlplus.engine.tools.YQLPlusRun.java

@SuppressWarnings("unchecked")
public int run(CommandLine command) throws Exception {
    String script = null;/*from w  w  w. ja  v a  2s . co  m*/
    String filename = null;
    if (command.hasOption("command")) {
        script = command.getOptionValue("command");
        filename = "<command line>";
    }
    List<String> scriptAndArgs = (List<String>) command.getArgList();
    if (filename == null && scriptAndArgs.size() < 1) {
        System.err.println("No script specified.");
        return -1;
    } else if (script == null) {
        filename = scriptAndArgs.get(0);
        Path scriptPath = Paths.get(filename);
        if (!Files.isRegularFile(scriptPath)) {
            System.err.println(scriptPath + " is not a file.");
            return -1;
        }
        script = Charsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(scriptPath))).toString();
    }
    List<String> paths = Lists.newArrayList();
    if (command.hasOption("path")) {
        paths.addAll(Arrays.asList(command.getOptionValues("path")));
    }
    // TODO: this isn't going to be very interesting without some sources
    Injector injector = Guice.createInjector(new JavaEngineModule());
    YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
    CompiledProgram program = compiler.compile(script);
    if (command.hasOption("source")) {
        program.dump(System.out);
        return 0;
    }
    // TODO: read command line arguments to pass to program
    ExecutorService outputThreads = Executors.newSingleThreadExecutor();
    ProgramResult result = program.run(Maps.<String, Object>newHashMap(), true);
    for (String name : result.getResultNames()) {
        final ListenableFuture<YQLResultSet> future = result.getResult(name);
        future.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    YQLResultSet resultSet = future.get();
                    System.out.println(new String((byte[]) resultSet.getResult()));
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }

            }
        }, outputThreads);
    }
    Future<TraceRequest> done = result.getEnd();
    try {
        done.get(10000L, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException | TimeoutException e) {
        e.printStackTrace();
    }
    outputThreads.awaitTermination(1L, TimeUnit.SECONDS);
    return 0;
}

From source file:com.yahoo.omid.tso.TSOHandler.java

public void start() {
    this.flushThread = new FlushThread();
    this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override/*from  w  ww  .  j a va  2  s  . c o  m*/
        public Thread newThread(Runnable r) {
            Thread t = new Thread(Thread.currentThread().getThreadGroup(), r);
            t.setDaemon(true);
            t.setName("Flush Thread");
            return t;
        }
    });
    this.flushFuture = scheduledExecutor.schedule(flushThread, TSOState.FLUSH_TIMEOUT, TimeUnit.MILLISECONDS);
    this.executor = Executors.newSingleThreadExecutor();
}

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

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

    waitForState(server, ServerState.RUNNING);

    final int numClients = 5;
    final ExecutorService clientsExec = Executors.newCachedThreadPool();
    for (int i = 0; i < numClients; i++) {
        clientsExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    invokeClient("testMultipleClients", port);
                } catch (InterruptedException e) {
                    Assert.fail(e.getMessage());
                }
            }
        });
    }
    clientsExec.awaitTermination(10, TimeUnit.SECONDS);
    clientsExec.shutdown();
    serverExec.shutdown();
}

From source file:com.jtech.iaf.CityBikesTransport.java

@Override
public void sendTransportEvent(Object event, TimestampSet timestampSet) throws TransportException {
    totalReceived++;//from ww w  . java  2s  . c  o m

    if (!(event instanceof NormalisedEvent)) {
        throw new TransportException("Invalid event type " + event.getClass(),
                TransportException.DECODINGFAILURE);
    }

    NormalisedEvent normalisedEvent = (NormalisedEvent) event;
    String type = normalisedEvent.findValue("__type");
    if (type != null && type.equals("Start")) {
        if (startRequested)
            return;
        logger.info("Received request to start");
        startRequested = true;
        exService = Executors.newSingleThreadExecutor();
        scheduler = new Scheduler();
        poll();

        if (pollingSchedule != null && !pollingSchedule.equals("none")) {
            scheduler.schedule(pollingSchedule, new Runnable() {
                public void run() {
                    poll();
                }
            });
            scheduler.start();
        }
    } else if (type != null && type.equals("Stop")) {
        if (!startRequested)
            return;
        logger.info("Received request to stop");
        startRequested = false;
        exService.shutdownNow();
        scheduler.stop();
    } else if (type != null && type.equals("Poll")) {
        if (!startRequested)
            return;
        logger.info("Received request to poll for data");
        poll();
    }
}

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

public static void postActiveStates(final String id, final List<String> activeStates,
        final List<String> allActiveStates) {
    if (getEventAdmin() == null)
        return;/*from w ww  . ja  v a 2 s  .com*/
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override
        public void run() {
            getEventAdmin().postEvent(new SCXMLActiveStatesEvent(id, activeStates, allActiveStates));
        }
    });
}