Example usage for java.util.concurrent Future isDone

List of usage examples for java.util.concurrent Future isDone

Introduction

In this page you can find the example usage for java.util.concurrent Future isDone.

Prototype

boolean isDone();

Source Link

Document

Returns true if this task completed.

Usage

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 ww.ja v a  2  s  . co  m*/
    Integer bytesRead = result.get();
    System.out.println("Bytes read [" + bytesRead + "]");
}

From source file:Main.java

public static void main(final String[] args) throws Exception {
    Random RND = new Random();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    List<Future<String>> results = new ArrayList<>(10);
    for (int i = 0; i < 10; i++) {
        results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
    }//from   www .java2 s.com
    es.shutdown();
    while (!results.isEmpty()) {
        Iterator<Future<String>> i = results.iterator();
        while (i.hasNext()) {
            Future<String> f = i.next();
            if (f.isDone()) {
                System.out.println(f.get());
                i.remove();
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("test.txt");

    try (AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE,
            StandardOpenOption.CREATE)) {
        ByteBuffer dataBuffer = getDataBuffer();
        Future<Integer> result = afc.write(dataBuffer, 0);
        while (!result.isDone()) {
            System.out.println("Sleeping for 2  seconds...");
            Thread.sleep(2000);//ww w.  ja v  a2s  .  c  o m
        }
        int writtenBytes = result.get();
        System.out.format("%s bytes written  to  %s%n", writtenBytes, path.toAbsolutePath());

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.bookkeeper.benchmark.TestClient.java

/**
 * First says if entries should be written to BookKeeper (0) or to the local
 * disk (1). Second parameter is an integer defining the length of a ledger entry.
 * Third parameter is the number of writes.
 *
 * @param args/*from   w w  w  . j a  v  a2s.c  om*/
 */
public static void main(String[] args) throws ParseException {
    Options options = new Options();
    options.addOption("length", true, "Length of packets being written. Default 1024");
    options.addOption("target", true, "Target medium to write to. Options are bk, fs & hdfs. Default fs");
    options.addOption("runfor", true, "Number of seconds to run for. Default 60");
    options.addOption("path", true, "Path to write to. fs & hdfs only. Default /foobar");
    options.addOption("zkservers", true,
            "ZooKeeper servers, comma separated. bk only. Default localhost:2181.");
    options.addOption("bkensemble", true, "BookKeeper ledger ensemble size. bk only. Default 3");
    options.addOption("bkquorum", true, "BookKeeper ledger quorum size. bk only. Default 2");
    options.addOption("bkthrottle", true, "BookKeeper throttle size. bk only. Default 10000");
    options.addOption("sync", false, "Use synchronous writes with BookKeeper. bk only.");
    options.addOption("numconcurrent", true, "Number of concurrently clients. Default 1");
    options.addOption("timeout", true, "Number of seconds after which to give up");
    options.addOption("help", false, "This message");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("TestClient <options>", options);
        System.exit(-1);
    }

    int length = Integer.parseInt(cmd.getOptionValue("length", "1024"));
    String target = cmd.getOptionValue("target", "fs");
    long runfor = Long.parseLong(cmd.getOptionValue("runfor", "60")) * 1000;

    StringBuilder sb = new StringBuilder();
    while (length-- > 0) {
        sb.append('a');
    }

    Timer timeouter = new Timer();
    if (cmd.hasOption("timeout")) {
        final long timeout = Long.parseLong(cmd.getOptionValue("timeout", "360")) * 1000;

        timeouter.schedule(new TimerTask() {
            public void run() {
                System.err.println("Timing out benchmark after " + timeout + "ms");
                System.exit(-1);
            }
        }, timeout);
    }

    BookKeeper bkc = null;
    try {
        int numFiles = Integer.parseInt(cmd.getOptionValue("numconcurrent", "1"));
        int numThreads = Math.min(numFiles, 1000);
        byte[] data = sb.toString().getBytes(UTF_8);
        long runid = System.currentTimeMillis();
        List<Callable<Long>> clients = new ArrayList<Callable<Long>>();

        if (target.equals("bk")) {
            String zkservers = cmd.getOptionValue("zkservers", "localhost:2181");
            int bkensemble = Integer.parseInt(cmd.getOptionValue("bkensemble", "3"));
            int bkquorum = Integer.parseInt(cmd.getOptionValue("bkquorum", "2"));
            int bkthrottle = Integer.parseInt(cmd.getOptionValue("bkthrottle", "10000"));

            ClientConfiguration conf = new ClientConfiguration();
            conf.setThrottleValue(bkthrottle);
            conf.setZkServers(zkservers);

            bkc = new BookKeeper(conf);
            List<LedgerHandle> handles = new ArrayList<LedgerHandle>();
            for (int i = 0; i < numFiles; i++) {
                handles.add(bkc.createLedger(bkensemble, bkquorum, DigestType.CRC32, new byte[] { 'a', 'b' }));
            }
            for (int i = 0; i < numFiles; i++) {
                clients.add(new BKClient(handles, data, runfor, cmd.hasOption("sync")));
            }
        } else if (target.equals("hdfs")) {
            FileSystem fs = FileSystem.get(new Configuration());
            LOG.info("Default replication for HDFS: {}", fs.getDefaultReplication());

            List<FSDataOutputStream> streams = new ArrayList<FSDataOutputStream>();
            for (int i = 0; i < numFiles; i++) {
                String path = cmd.getOptionValue("path", "/foobar");
                streams.add(fs.create(new Path(path + runid + "_" + i)));
            }

            for (int i = 0; i < numThreads; i++) {
                clients.add(new HDFSClient(streams, data, runfor));
            }
        } else if (target.equals("fs")) {
            List<FileOutputStream> streams = new ArrayList<FileOutputStream>();
            for (int i = 0; i < numFiles; i++) {
                String path = cmd.getOptionValue("path", "/foobar " + i);
                streams.add(new FileOutputStream(path + runid + "_" + i));
            }

            for (int i = 0; i < numThreads; i++) {
                clients.add(new FileClient(streams, data, runfor));
            }
        } else {
            LOG.error("Unknown option: " + target);
            throw new IllegalArgumentException("Unknown target " + target);
        }

        ExecutorService executor = Executors.newFixedThreadPool(numThreads);
        long start = System.currentTimeMillis();

        List<Future<Long>> results = executor.invokeAll(clients, 10, TimeUnit.MINUTES);
        long end = System.currentTimeMillis();
        long count = 0;
        for (Future<Long> r : results) {
            if (!r.isDone()) {
                LOG.warn("Job didn't complete");
                System.exit(2);
            }
            long c = r.get();
            if (c == 0) {
                LOG.warn("Task didn't complete");
            }
            count += c;
        }
        long time = end - start;
        LOG.info("Finished processing writes (ms): {} TPT: {} op/s", time, count / ((double) time / 1000));
        executor.shutdown();
    } catch (ExecutionException ee) {
        LOG.error("Exception in worker", ee);
    } catch (KeeperException ke) {
        LOG.error("Error accessing zookeeper", ke);
    } catch (BKException e) {
        LOG.error("Error accessing bookkeeper", e);
    } catch (IOException ioe) {
        LOG.error("I/O exception during benchmark", ioe);
    } catch (InterruptedException ie) {
        LOG.error("Benchmark interrupted", ie);
    } finally {
        if (bkc != null) {
            try {
                bkc.close();
            } catch (BKException bke) {
                LOG.error("Error closing bookkeeper client", bke);
            } catch (InterruptedException ie) {
                LOG.warn("Interrupted closing bookkeeper client", ie);
            }
        }
    }
    timeouter.cancel();
}

From source file:Main.java

private static boolean cancel(final Future<?> future) {
    return future.isDone() || future.isCancelled() || future.cancel(true);
}

From source file:Main.java

public static boolean isDone(final Future<?> future) {
    return (future != null) && future.isDone();
}

From source file:Main.java

public static void cancelTask(Future<?> task, boolean interrupt) {
    if (task != null && !task.isDone()) {
        task.cancel(interrupt);/*w  ww.j  av  a2  s .  com*/
    }
}

From source file:Main.java

public static <T> void iteratorResult(List<Future<T>> results) {
    // TODO Auto-generated method stub
    for (Future<T> future : results) {
        try {//from  www. j  a  v a 2 s . com
            System.out.println(future.isDone() + "," + future.get());
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:org.sipfoundry.sipxconfig.admin.configdiag.ConfigurationDiagnosticContextImpl.java

/**
 * Checks if any tests are currently in progress
 *
 * @param results list of test results - can be null
 * @return true is at least one future is not completed yet
 *//*from   w ww .ja  v  a2 s .  c o m*/
static <T> boolean isInProgress(List<Future<T>> results) {
    if (results == null) {
        return false;
    }
    for (Future<T> future : results) {
        if (!future.isDone()) {
            return true;
        }
    }
    return false;
}

From source file:org.apache.hadoop.hbase.io.hfile.PrefetchExecutor.java

public static boolean isCompleted(Path path) {
    Future<?> future = prefetchFutures.get(path);
    if (future != null) {
        return future.isDone();
    }//from w w  w .j  ava  2s .  com
    return true;
}