Java Code Examples for java.util.concurrent.Executors

The following are top voted examples for showing how to use java.util.concurrent.Executors. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: iot-server-appliances   File: AgentCoreOperations.java View source code Vote up 7 votes
public static void startGPIOReader(){
	Runnable gpioReader = new Runnable() {
		@Override
		public void run() {
			String returnVal = readTemperatureFromPi();
			double temperature = Double.parseDouble(returnVal.split(":")[0].replace("C", ""));
			double humidity = Double.parseDouble(returnVal.split(":")[1].replace("%", ""));

			agentManager.setTemperature(temperature);
			agentManager.setHumidity(humidity);
		}
	};

	ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
	service.scheduleAtFixedRate(gpioReader, 0, agentManager.getAgentConfigs().getDataPushInterval()*100, TimeUnit.MILLISECONDS);
}
 
Example 2
Project: led-server   File: ServerIntegrationTest.java View source code Vote up 6 votes
@Test
public void shouldProcessConcurrentGets() throws Exception {

    int threads = 300;
    final HttpGet get = new HttpGet("http://localhost:8889/test");
    final CyclicBarrier barrier = new CyclicBarrier(threads);
    final AtomicInteger done = new AtomicInteger();
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < threads; i++) {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    final DefaultHttpClient client = new DefaultHttpClient();
                    barrier.await();
                    HttpResponse response = client.execute(get);

                    EntityUtils.consumeQuietly(response.getEntity());
                    assertEquals(200, response.getStatusLine()
                            .getStatusCode());
                    done.incrementAndGet();
                } catch (InterruptedException | BrokenBarrierException
                        | IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        });
    }

    while (done.get() != threads) {
        // wait
        Thread.sleep(500);

    }
    System.err.println("DONE, Time: "
            + (System.currentTimeMillis() - startTime));

}
 
Example 3
Project: led-server   File: Server.java View source code Vote up 6 votes
public void start() throws IOException {
    LOG.debug("Starting LED Server on Port: " + configuration.getPort());
    group = AsynchronousChannelGroup.withCachedThreadPool(
            Executors.newCachedThreadPool(), configuration.getThreads());
    final AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel
            .open(group).bind(
                    new InetSocketAddress(configuration.getPort()));
    serverSocketChannel
            .setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
    serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

    serverSocketChannel.accept(null, new HttpProtocolHandler(
            serverSocketChannel, configuration.getHandlerFactory(),
            configuration.getMaxPostMB()));
    started = true;
    LOG.debug("Server started successfully");
    try {
        group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
        LOG.info("Terminating ");
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }

}
 
Example 4
Project: SliderBar   File: SliderLayoutListener.java View source code Vote up 6 votes
/**
 * Constructor that creates the layout listener for the Sliders
 * 
 * @param sliders
 *            A [email protected] List} containing all the [email protected] SliderBar}s defined
 * @param caller
 *            The [email protected] Fragment} that calls the layout listener (the [email protected] Fragment} containing the [email protected] SliderBar}s). This is
 *            used to send on the event when the listener detects a change
 *            in the sliders.
 */
public SliderLayoutListener(List<SliderBar> sliders, SliderFragment caller) {
	this.sliders = sliders;
	this.caller = caller;
	sliderDragging = false;
	actionQueue = new ArrayList<Integer>();
	slidersBeingDragged = new ArrayList<SliderBar>();
	inputDelay = Executors.newScheduledThreadPool(1);
}
 
Example 5
Project: CDDA-Tileset-Editor   File: ProgressDialog.java View source code Vote up 6 votes
public void execute(Runnable runnable) {
	service = Executors.newSingleThreadExecutor(new ThreadFactory() {
		@Override
		public Thread newThread(Runnable r) {
			Thread t = Executors.defaultThreadFactory().newThread(r);
			t.setDaemon(true);
			return t;
		}
	});
	service.submit(runnable);
	setVisible(true);
	service.shutdownNow();
	dispose();
}
 
Example 6
Project: netty4.0.27Learn   File: AbstractScheduledEventExecutor.java View source code Vote up 6 votes
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
    ObjectUtil.checkNotNull(command, "command");
    ObjectUtil.checkNotNull(unit, "unit");
    if (initialDelay < 0) {
        throw new IllegalArgumentException(
                String.format("initialDelay: %d (expected: >= 0)", initialDelay));
    }
    if (period <= 0) {
        throw new IllegalArgumentException(
                String.format("period: %d (expected: > 0)", period));
    }

    return schedule(new ScheduledFutureTask<Void>(
            this, Executors.<Void>callable(command, null),
            ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), unit.toNanos(period)));
}
 
Example 7
Project: idnadrev   File: AsciiDocParserTest.java View source code Vote up 6 votes
@Test
public void testMultiThreadParsing() throws Exception {
  ExecutorService service = Executors.newWorkStealingPool();
  String expectedResult = asciiDocParser.parse(asciiDocSimple);
  CompletableFuture<Void> all = null;
  try {
    for (int i = 0; i < Runtime.getRuntime().availableProcessors() * 100; i++) {
      CompletableFuture<Void> result = CompletableFuture.supplyAsync(() -> asciiDocParser.parse(asciiDocSimple), service)//
        .thenAccept((input) -> assertEquals(expectedResult, input));

      if (all == null) {
        all = result;
      } else {
        all = CompletableFuture.allOf(all, result);
      }
    }

    all.join();
  } finally {
    service.shutdownNow();
    service.awaitTermination(5, TimeUnit.SECONDS);
  }
}
 
Example 8
Project: browserid-verifier   File: Verifier.java View source code Vote up 5 votes
/***
 * @param assertion
 * @param audience
 * @param timeOut
 *            To wait for the verification process. Unlike
 *            the low level [email protected] URLConnection#setConnectTimeout(int)} and
 *            [email protected] URLConnection#setReadTimeout(int)} which set different
 *            time outs for the connection and read processes, this a global
 *            time out for the entire verification process.
 *            Its value should be > 0.
 * @param timeUnit    
 *
 * @return the result of the verification
 * 
 * @throws [email protected] BrowserIDResponse} if there is a failure in the
 *         verification process
 * @throws [email protected] IllegalArgumentException} if the arguments are invalid.
 */
public BrowserIDResponse verify(final String assertion,
		final String audience, final long timeOut, final TimeUnit timeUnit) {
	log.debug("assertion: '{}' audience: '{}'", assertion, audience);
	if (assertion == null || !(assertion.length() > 0)) {
		throw new IllegalArgumentException("assertion is mandatory");
	}
	if (audience == null || !(audience.length() > 0)) {
		throw new IllegalArgumentException("audience is mandatory");
	}
	if (timeOut <= 0) {
		throw new IllegalArgumentException("Timeout value should be > 0");
	}

	try {
		final JSONRequest body = new JSONRequest(assertion, audience);
		log.debug("Verifying: '{}' using: '{}'", body.toString(), this.url);
		final URL verifierURL = new URL(this.url);
		final HttpsURLConnection connection = prepareConnection(verifierURL);
		String response = "";
		/* Execute the verification task */
		final ExecutorService verifierExecutor = Executors
				.newSingleThreadExecutor();
		final Callable<String> verifyTask = new VerifyTask(connection,
				body);
		final Future<String> verifyExcution = verifierExecutor
				.submit(verifyTask);

		verifierExecutor.shutdown();
		try {
			response = verifyExcution.get(timeOut, timeUnit);

		} catch (final InterruptedException | TimeoutException thExc) {
			throw new BrowserIDException(thExc);

		} catch (final ExecutionException execExc) {
			throw new BrowserIDException(execExc.getCause());
		}

		log.debug("Response from verifier: [{}] '{}'",
				connection.getResponseCode(), response);

		return new BrowserIDResponse(response);

	} catch (final IOException ioexc) {
		throw new BrowserIDException(ioexc);
	}
}