List of usage examples for java.util.concurrent Future get
V get() throws InterruptedException, ExecutionException;
From source file:Test.java
public static void main(String[] args) throws Exception { Path file = Paths.get("/usr/a.txt"); AsynchronousFileChannel channel = AsynchronousFileChannel.open(file); ByteBuffer buffer = ByteBuffer.allocate(100_000); Future<Integer> result = channel.read(buffer, 0); while (!result.isDone()) { ProfitCalculator.calculateTax(); }//from w w w .j a va2s.c o m Integer bytesRead = result.get(); System.out.println("Bytes read [" + bytesRead + "]"); }
From source file:disko.flow.analyzers.socket.SocketTransmitter.java
public static void main(String[] args) throws InterruptedException, ExecutionException { AnalysisContext<TextDocument> ctx = null; DataFlowNetwork<AnalysisContext<TextDocument>> network = new DataFlowNetwork<AnalysisContext<TextDocument>>( ctx);//from w w w . j a v a2 s . c o m network.addChannel(new Channel<String>(SentenceAnalyzer.TEXT_CHANNEL, "\0")); network.addChannel(new Channel<SentenceAnn>(SentenceAnalyzer.SENTENCE_CHANNEL, new SentenceAnn(0, 0))); network.addNode(new FileReaderAnalyzer<AnalysisContext<TextDocument>>("test/headstart.txt"), new String[] {}, new String[] { SentenceAnalyzer.TEXT_CHANNEL }); network.addNode(new SentenceAnalyzer(), new String[] { SentenceAnalyzer.TEXT_CHANNEL }, new String[] { SentenceAnalyzer.SENTENCE_CHANNEL }); network.addNode(new SocketTransmitter<AnalysisContext<TextDocument>>("localhost", 10000), new String[] { SentenceAnalyzer.SENTENCE_CHANNEL }, new String[] {}); while (true) { final Future<?> finished = network.start(); finished.get(); } }
From source file:Pong.java
public static void main(String... args) throws Exception { System.setProperty("os.max.pid.bits", "16"); Options options = new Options(); options.addOption("i", true, "Input chronicle path"); options.addOption("n", true, "Number of entries to write"); options.addOption("w", true, "Number of writer threads"); options.addOption("r", true, "Number of reader threads"); options.addOption("x", false, "Delete the output chronicle at startup"); CommandLine cmd = new DefaultParser().parse(options, args); final Path output = Paths.get(cmd.getOptionValue("o", "/tmp/__test/chr")); final long maxCount = Long.parseLong(cmd.getOptionValue("n", "10000000")); final int writerThreadCount = Integer.parseInt(cmd.getOptionValue("w", "4")); final int readerThreadCount = Integer.parseInt(cmd.getOptionValue("r", "4")); final boolean deleteOnStartup = cmd.hasOption("x"); if (deleteOnStartup) { FileUtil.removeRecursive(output); }/*w w w.ja va2 s . com*/ final Chronicle chr = ChronicleQueueBuilder.vanilla(output.toFile()).build(); final ExecutorService executor = Executors.newFixedThreadPool(4); final List<Future<?>> futures = new ArrayList<>(); final long totalCount = writerThreadCount * maxCount; final long t0 = System.nanoTime(); for (int i = 0; i != readerThreadCount; ++i) { final int tid = i; futures.add(executor.submit((Runnable) () -> { try { IntLongMap counts = HashIntLongMaps.newMutableMap(); ExcerptTailer tailer = chr.createTailer(); final StringBuilder sb1 = new StringBuilder(); final StringBuilder sb2 = new StringBuilder(); long count = 0; while (count != totalCount) { if (!tailer.nextIndex()) continue; final int id = tailer.readInt(); final long val = tailer.readStopBit(); final long longValue = tailer.readLong(); sb1.setLength(0); sb2.setLength(0); tailer.read8bitText(sb1); tailer.read8bitText(sb2); if (counts.addValue(id, 1) - 1 != val || longValue != 0x0badcafedeadbeefL || !StringInterner.isEqual("FooBar", sb1) || !StringInterner.isEqual("AnotherFooBar", sb2)) { System.out.println("Unexpected value " + id + ", " + val + ", " + Long.toHexString(longValue) + ", " + sb1.toString() + ", " + sb2.toString()); return; } ++count; if (count % 1_000_000 == 0) { long t1 = System.nanoTime(); System.out.println(tid + " " + (t1 - t0) / 1e6 + " ms"); } } } catch (IOException e) { e.printStackTrace(); } })); } for (Future f : futures) { f.get(); } executor.shutdownNow(); final long t1 = System.nanoTime(); System.out.println("Done. Rough time=" + (t1 - t0) / 1e6 + " ms"); }
From source file:Main.java
public static void main(String[] args) throws Exception { ExecutorService ex = Executors.newSingleThreadExecutor(); Future<Integer> future = // This Lambda evaluated to Callable<Integer> ex.submit(() -> ThreadLocalRandom.current().nextInt(1, 10)); System.out.println("Randomized value: " + future.get()); }
From source file:Main.java
public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService ex = Executors.newSingleThreadExecutor(); Future<Integer> future = // This Lambda evaluated to Callable<Integer> ex.submit(() -> ThreadLocalRandom.current().nextInt(1, 10)); System.out.println("Randomized value: " + future.get()); }
From source file:com.ok2c.lightmtp.examples.SendMailExample.java
public static void main(final String[] args) throws Exception { if (args.length < 3) { System.out.println("Usage: sender recipient1[;recipient2;recipient3;...] file"); System.exit(0);//from ww w.j av a2s . co m } String sender = args[0]; List<String> recipients = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(args[1], ";"); while (tokenizer.hasMoreTokens()) { String s = tokenizer.nextToken(); s = s.trim(); if (s.length() > 0) { recipients.add(s); } } File src = new File(args[2]); if (!src.exists()) { System.out.println("File '" + src + "' does not exist"); System.exit(0); } DeliveryRequest request = new BasicDeliveryRequest(sender, recipients, new FileSource(src)); MailUserAgent mua = new DefaultMailUserAgent(TransportType.SMTP, IOReactorConfig.DEFAULT); mua.start(); try { InetSocketAddress address = new InetSocketAddress("localhost", 2525); Future<DeliveryResult> future = mua.deliver(new SessionEndpoint(address), 0, request, null); DeliveryResult result = future.get(); System.out.println("Delivery result: " + result); } finally { mua.shutdown(); } }
From source file:ThreadPoolTest.java
public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): "); String directory = in.nextLine(); System.out.print("Enter keyword (e.g. volatile): "); String keyword = in.nextLine(); ExecutorService pool = Executors.newCachedThreadPool(); MatchCounter counter = new MatchCounter(new File(directory), keyword, pool); Future<Integer> result = pool.submit(counter); try {// w w w . j a va2 s. co m System.out.println(result.get() + " matching files."); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { } pool.shutdown(); int largestPoolSize = ((ThreadPoolExecutor) pool).getLargestPoolSize(); System.out.println("largest pool size=" + largestPoolSize); }
From source file:Test.java
public static void main(String[] args) throws Exception { AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("/asynchronous.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); Future<Integer> writeFuture1 = fileChannel.write(ByteBuffer.wrap("Sample".getBytes()), 0); Future<Integer> writeFuture2 = fileChannel.write(ByteBuffer.wrap("Box".getBytes()), 0); int result;//from w ww . j a v a2 s . co m result = writeFuture1.get(); System.out.println("Sample write completed with " + result + " bytes written"); result = writeFuture2.get(); System.out.println("Box write completed with " + result + " bytes written"); }
From source file:com.boonya.http.async.examples.nio.client.AsyncClientPipelined.java
public static void main(final String[] args) throws Exception { CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining(); try {/* w ww . j a va 2 s .com*/ httpclient.start(); HttpHost targetHost = new HttpHost("localhost", 8080); HttpGet[] resquests = { new HttpGet("/docs/index.html"), new HttpGet("/docs/introduction.html"), new HttpGet("/docs/setup.html"), new HttpGet("/docs/config/index.html") }; Future<List<HttpResponse>> future = httpclient.execute(targetHost, Arrays.<HttpRequest>asList(resquests), null); List<HttpResponse> responses = future.get(); System.out.println(responses); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
From source file:httpasync.AsyncClientPipelined.java
public static void main(final String[] args) throws Exception { CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining(); try {/* w ww. j av a 2s . c o m*/ httpclient.start(); HttpHost targetHost = new HttpHost("money.moneydj.com", 80); HttpGet[] resquests = { new HttpGet("/us/basic/basic0001/Person"), new HttpGet("/us/basic/basic0001/AA"), new HttpGet("/us/basic/basic0001/PSG"), // new HttpGet("/docs/introduction.html"), // new HttpGet("/docs/setup.html"), // new HttpGet("/docs/config/index.html") }; Future<List<HttpResponse>> future = httpclient.execute(targetHost, Arrays.<HttpRequest>asList(resquests), null); List<HttpResponse> responses = future.get(); responses.forEach(System.out::println); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }