Example usage for java.util.concurrent FutureTask get

List of usage examples for java.util.concurrent FutureTask get

Introduction

In this page you can find the example usage for java.util.concurrent FutureTask get.

Prototype

public V get() throws InterruptedException, ExecutionException 

Source Link

Usage

From source file:dk.dbc.opensearch.datadock.DatadockPool.java

/**
 * Checks the jobs submitted for execution
 * /*from   ww w.ja v a2 s.  com*/
 * if a Job throws an exception it is written to the log and the
 * datadock continues.
 *
 * @throws InterruptedException if the job.get() call is interrupted (by kill or otherwise).
 */
public void checkJobs() throws InterruptedException {
    log.debug("DatadockPool method checkJobs called");

    log.debug(String.format("job size = %s", jobs.size()));

    Set<IIdentifier> finishedJobs = new HashSet<IIdentifier>();
    for (IIdentifier id : jobs.keySet()) {
        FutureTask<Boolean> job = jobs.get(id);
        log.debug(String.format("job is done: %s", job.isDone()));
        if (job.isDone()) {
            Boolean success = Boolean.FALSE;

            try {
                log.debug("DatadockPool checking job");
                success = job.get();
            } catch (ExecutionException ee) {
                // getting exception from thread
                Throwable cause = ee.getCause();
                log.error(String.format("Exception caught for identifier: %s, from thread: '%s'", id, cause),
                        cause);

                log.info(String.format("Setting status to FAILURE for identifier: %s with message: '%s'", id,
                        cause.getMessage()));
                try {
                    String msg = cause.getMessage() == null ? cause.toString() : cause.getMessage(); // avoid giving null to setStatusFailure
                    harvester.setStatusFailure(id, msg);
                } catch (HarvesterUnknownIdentifierException ex) {
                    String error = String.format(
                            "Failed to set failure status for identifier: %s . Message: %s", id,
                            ex.getMessage());
                    log.error(error, ex);
                } catch (HarvesterInvalidStatusChangeException ex) {
                    String error = String.format(
                            "Failed to set failure status for identifier: %s . Message: %s", id,
                            ex.getMessage());
                    log.error(error, ex);
                } catch (HarvesterIOException ex) {
                    String error = String.format(
                            "Failed to set failure status for identifier: %s . Message: %s", id,
                            ex.getMessage());
                    log.error(error, ex);
                }
            }

            log.debug("DatadockPool adding to finished jobs");
            finishedJobs.add(id);
        }
    }

    for (IIdentifier finishedJobId : finishedJobs) {
        log.debug(String.format("Removing Job with id: %s. Remaining jobs: %s", finishedJobId, jobs.size()));
        jobs.remove(finishedJobId);
    }
}

From source file:com.bilibili.boxing.utils.CameraPickerHelper.java

/**
 * deal with the system camera's shot.//from  www . j av  a  2 s .  c o  m
 */
public boolean onActivityResult(final int requestCode, final int resultCode) {
    if (requestCode != REQ_CODE_CAMERA) {
        return false;
    }
    if (resultCode != Activity.RESULT_OK) {
        callbackError();
        return false;
    }
    FutureTask<Boolean> task = BoxingExecutor.getInstance().runWorker(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return rotateImage(resultCode);
        }
    });
    try {
        if (task != null && task.get()) {
            callbackFinish();
        } else {
            callbackError();
        }
    } catch (InterruptedException | ExecutionException ignore) {
        callbackError();
    }
    return true;
}

From source file:com.alibaba.napoli.metamorphosis.client.producer.ProducerZooKeeper.java

BrokerConnectionListener getBrokerConnectionListener(final String topic) {
    final FutureTask<BrokerConnectionListener> task = this.topicConnectionListeners.get(topic);
    if (task != null) {
        try {//from  w ww.ja  v a  2 s.  co m
            return task.get();
        } catch (final Exception e) {
            log.error("?BrokerConnectionListener", e);
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.googlecode.networklog.ExportDialog.java

public void exportLog(final Date startDate, final Date endDate, final File file) {
    MyLog.d("Exporting from " + dateFilenameFormat.format(startDate) + " to "
            + dateFilenameFormat.format(endDate) + " to path " + file.getAbsolutePath());

    final long end_timestamp = endDate.getTime();
    final LogfileLoader loader = new LogfileLoader();

    try {/*from w w w  . j a  va2s  .  c  o m*/
        loader.openLogfile(NetworkLog.settings.getLogFile());
    } catch (FileNotFoundException fnfe) {
        SysUtils.showError(context, context.getResources().getString(R.string.export_error_title),
                "No logfile found at " + NetworkLog.settings.getLogFile());
        return;
    } catch (Exception e) {
        SysUtils.showError(context, context.getResources().getString(R.string.export_error_title),
                "Error opening logfile: " + e.getMessage());
        return;
    }

    try {
        final long length = loader.getLength();

        if (length == 0) {
            SysUtils.showError(context, context.getResources().getString(R.string.export_error_title),
                    "Logfile empty -- nothing to export");
            return;
        }

        long possible_end_pos = loader.seekToTimestampPosition(endDate.getTime(), true);
        final long start_pos = loader.seekToTimestampPosition(startDate.getTime());

        if (possible_end_pos == -1) {
            possible_end_pos = length;
        }

        final long end_pos = possible_end_pos;

        if (start_pos == -1) {
            SysUtils.showError(context, context.getResources().getString(R.string.export_error_title),
                    "No entries found at " + dateDisplayFormat.format(startDate));
            return;
        }

        progress_max = (int) (end_pos - start_pos);
        progress = 0;

        CSVWriter open_writer;
        try {
            open_writer = new CSVWriter(new FileWriter(file));
        } catch (Exception e) {
            SysUtils.showError(context, context.getResources().getString(R.string.export_error_title),
                    "Error opening export file: " + e.getMessage());
            return;
        }
        final CSVWriter writer = open_writer;

        new Thread(new Runnable() {
            public void run() {
                try {
                    FutureTask showDialog = showProgressDialog(context);
                    showDialog.get(); // wait until showDialog task completes
                } catch (Exception e) {
                    // ignored
                }

                LogEntry entry;
                ApplicationsTracker.AppEntry appEntry;
                long processed_so_far = 0;
                long progress_increment_size = (long) ((end_pos - start_pos) * 0.01);
                long next_progress_increment = progress_increment_size;

                try {
                    String[] entries = new String[11];

                    entries[0] = "Timestamp";
                    entries[1] = "AppName";
                    entries[2] = "AppPackage";
                    entries[3] = "AppUid";
                    entries[4] = "In interface";
                    entries[5] = "Out interface";
                    entries[6] = "Source";
                    entries[7] = "Source Port";
                    entries[8] = "Destination";
                    entries[9] = "Destination Port";
                    entries[10] = "Length";

                    writer.writeNext(entries);

                    while (!canceled) {
                        entry = loader.readEntry();

                        processed_so_far = loader.getProcessedSoFar();

                        if (processed_so_far >= next_progress_increment) {
                            next_progress_increment += progress_increment_size;
                            progress = (int) processed_so_far;
                            if (progressDialog != null) {
                                progressDialog.setProgress(progress);
                            }
                        }

                        if (entry == null) {
                            // end of file
                            break;
                        }

                        if (entry.timestamp > end_timestamp) {
                            break;
                        }

                        appEntry = ApplicationsTracker.uidMap.get(entry.uidString);

                        entries[0] = Timestamp.getTimestamp(entry.timestamp);
                        entries[1] = appEntry == null ? "Uninstalled App" : appEntry.name;
                        entries[2] = appEntry == null ? "Uninstalled App" : appEntry.packageName;
                        entries[3] = entry.uidString;
                        entries[4] = entry.in;
                        entries[5] = entry.out;
                        entries[6] = entry.src;
                        entries[7] = StringPool.get(entry.spt);
                        entries[8] = entry.dst;
                        entries[9] = StringPool.get(entry.dpt);
                        entries[10] = StringPool.get(entry.len);

                        writer.writeNext(entries);
                    }
                } catch (Exception e) {
                    SysUtils.showError(context, context.getResources().getString(R.string.export_error_title),
                            "Error exporting logfile: " + e.getMessage());
                } finally {
                    try {
                        loader.closeLogfile();
                    } catch (Exception e) {
                        // ignored
                    }

                    try {
                        writer.close();
                    } catch (Exception e) {
                        // ignored
                    }

                    NetworkLog.handler.post(new Runnable() {
                        public void run() {
                            if (progressDialog != null) {
                                progressDialog.dismiss();
                                progressDialog = null;
                            }
                        }
                    });
                }
            }
        }, "ExportLogfile").start();
    } catch (Exception e) {
        SysUtils.showError(context, context.getResources().getString(R.string.export_error_title),
                "Error exporting logfile: " + e.getMessage());
    }
}

From source file:ubic.gemma.core.loader.util.fetcher.HttpFetcher.java

protected Collection<LocalFile> doTask(FutureTask<Boolean> future, String seekFile, String outputFileName) {
    Executors.newSingleThreadExecutor().execute(future);
    try {// w  w  w. j ava  2  s  . c  om

        while (!future.isDone()) {
            try {
                Thread.sleep(AbstractFetcher.INFO_UPDATE_INTERVAL);
            } catch (InterruptedException ignored) {

            }
            AbstractFetcher.log.info((new File(outputFileName).length() + " bytes read"));
        }
        if (future.get()) {
            return this.listFiles(seekFile, outputFileName);
        }
    } catch (ExecutionException | IOException e) {
        throw new RuntimeException("Couldn't fetch file for " + seekFile, e);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted: Couldn't fetch file for " + seekFile, e);
    }
    throw new RuntimeException("Couldn't fetch file for " + seekFile);
}

From source file:com.googlecode.icegem.cacheutils.regioncomparator.CompareTool.java

public void execute(String[] args, boolean debugEnabled, boolean quiet) {
    AdminDistributedSystem adminDs = AdminDistributedSystemFactory
            .getDistributedSystem(AdminDistributedSystemFactory.defineDistributedSystem());
    adminDs.connect();/*  w  w  w  . j  a va 2 s.c  o m*/

    parseCommandLineArguments(args);

    List<Pool> poolList = new ArrayList<Pool>();
    if (serversOption != null && serversOption.length() > 0)
        for (String serverOption : serversOption.split(",")) {
            String serverHost = serverOption.substring(0, serverOption.indexOf("["));
            String serverPort = serverOption.substring(serverOption.indexOf("[") + 1,
                    serverOption.indexOf("]"));
            poolList.add(PoolManager.createFactory().addServer(serverHost, Integer.parseInt(serverPort))
                    .create("poolTo" + serverHost + serverPort));
        }
    if (locatorsProperties != null && !locatorsProperties.isEmpty())
        for (Object poolOption : locatorsProperties.keySet()) {
            String locator = (String) locatorsProperties.get(poolOption);
            String serverHost = locator.substring(0, locator.indexOf("["));
            String serverPort = locator.substring(locator.indexOf("[") + 1, locator.indexOf("]"));
            poolList.add(PoolManager.createFactory().addLocator(serverHost, Integer.parseInt(serverPort)) //todo: check when we have two identical locators options: exception a pool name already exist
                    .create("poolTo" + serverHost + serverPort));
        }

    //todo: insert checking that each cluster contains region and one's type is equal (Partitioned, Replicated)

    boolean partitioned = false; //todo: insert CLI usage  + throw exception if real region has another type

    List<ServerLocation> serverFromPool = new ArrayList<ServerLocation>();
    List<Pool> emptyPools = new ArrayList<Pool>(); //contains pool with no available servers
    for (Pool pool : poolList) {
        List<ServerLocation> allServers = null;
        if (!pool.getLocators().isEmpty())
            allServers = ((AutoConnectionSourceImpl) ((PoolImpl) pool).getConnectionSource()).findAllServers(); //todo: ConnectionError if locator doesn't exist
        else if (!pool.getServers().isEmpty())
            allServers = Arrays
                    .asList((((PoolImpl) pool).getConnectionSource()).findServer(Collections.emptySet()));

        if (allServers != null)
            serverFromPool.addAll(allServers);
        else {
            log.info("not found servers on locator {}", pool);
            emptyPools.add(pool);
        }
    }
    poolList.removeAll(emptyPools);

    if (serverFromPool.size() == 0) {
        log.info("no servers available");
        return;
    }

    printServerLocationDetails(serverFromPool);

    //source for comparison //todo: if this node doesn't contain region! it's problem
    Pool sourcePool;
    if (!partitioned) {
        int randomServerLocation = new Random().nextInt(serverFromPool.size());
        sourcePool = PoolManager.createFactory()
                .addServer(serverFromPool.get(randomServerLocation).getHostName(),
                        serverFromPool.get(randomServerLocation).getPort())
                .create("target");
    } else {
        sourcePool = poolList.get(0);
        poolList.remove(0);
    }

    FunctionService.registerFunction(new RegionInfoFunction());
    ResultCollector regionInfoResult = FunctionService.onServers(sourcePool).withArgs(regionName)
            .execute(new RegionInfoFunction());

    Map regionInfo = (HashMap) ((ArrayList) regionInfoResult.getResult()).get(0);
    System.out.println("region info: " + regionInfo);

    int totalNumBuckets = (Integer) regionInfo.get("totalNumBuckets");
    //log.debug("total keys' batch counts is ", totalNumBuckets);
    System.out.println("total keys' batch counts is " + totalNumBuckets);
    KeyExtractor keyExtractor = new KeyExtractor(regionName, sourcePool, partitioned, totalNumBuckets);

    Map<String, Map<String, Set>> clusterDifference = new HashMap<String, Map<String, Set>>(); //key: memeberId list: absent keys, diff values

    List<PoolResult> taskResults = new ArrayList<PoolResult>();
    List<Future<PoolResult>> collectTasks = new ArrayList<Future<PoolResult>>(poolList.size());
    ExecutorService executorService = Executors.newFixedThreadPool(poolList.size());
    while (keyExtractor.hasKeys()) {
        Set keys = keyExtractor.getNextKeysBatch();
        System.out.println("keys to check: " + keys);
        for (Pool nextPool : poolList)
            collectTasks.add(executorService.submit(new CollectorTask(keys, nextPool, regionName)));
        System.out.println("active tasks: " + collectTasks.size());
        try {
            //for (Future<ResultCollector> futureTask : collectTasks) {
            for (Future<PoolResult> futureTask : collectTasks) {
                taskResults.add(futureTask.get());
            }
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        } catch (ExecutionException ee) {
            ee.printStackTrace();
        }
        collectTasks.clear();

        System.out.println("compare contents..");
        //getting source contents
        Map sourceData = new HashMap();

        //getting source map
        FutureTask<PoolResult> ft = new FutureTask<PoolResult>(new CollectorTask(keys, sourcePool, regionName));
        ft.run();
        try {
            PoolResult rc = ft.get();
            List poolResult = (List) rc.getResultCollector().getResult();
            for (Object singleResult : poolResult) {
                sourceData.putAll((Map) ((HashMap) singleResult).get("map"));
            }
        } catch (Exception e) {
            throw new RuntimeException("error getting key-hash from pool: " + sourcePool, e);
        }
        //todo: aggregate members' data from one cluster

        System.out.println("source data is: " + sourceData);
        //for (ResultCollector taskResultFromPool : taskResults) {
        for (PoolResult taskResultFromPool : taskResults) {
            List poolResult = (ArrayList) taskResultFromPool.getResultCollector().getResult();
            if (!partitioned) {
                for (Object resultFromMember : poolResult) {
                    Map result = (HashMap) resultFromMember;
                    String memberId = (String) result.get("memberId");
                    if (regionInfo.get("id").equals(result.get("memberId"))) //for replicated region
                        continue;
                    Map<String, Set> aggregationInfo = compareAndAggregate(sourceData,
                            (HashMap) result.get("map"));
                    System.out.println("result of comparing is: " + aggregationInfo);
                    if (!clusterDifference.containsKey(memberId)) {
                        aggregationInfo.put("absentKeys", new HashSet());
                        clusterDifference.put(memberId, aggregationInfo);
                    } else {
                        Map<String, Set> difference = clusterDifference.get(memberId);
                        difference.get("absentKeys").addAll((Set) result.get("absentKeys"));
                        difference.get("diffValues").addAll(aggregationInfo.get("diffValues"));
                        clusterDifference.put(memberId, difference);
                    }
                }
            } else {
                Map targetData = new HashMap();
                Set absentKeysFromPool = new HashSet();

                //aggregate data from different members with partition region
                for (Object resultFromMember : poolResult) {
                    targetData.putAll((Map) ((HashMap) resultFromMember).get("map"));
                    absentKeysFromPool.addAll((Set) ((HashMap) resultFromMember).get("absentKeys"));
                }

                Map<String, Set> aggregationInfo = compareAndAggregate(sourceData, targetData);
                System.out.println("result of comparing is: " + aggregationInfo);
                String keyForPartitionRegionType = taskResultFromPool.getPool().toString();
                if (!clusterDifference.containsKey(keyForPartitionRegionType)) {
                    clusterDifference.put(keyForPartitionRegionType, aggregationInfo);
                } else {
                    Map<String, Set> difference = clusterDifference.get(keyForPartitionRegionType);
                    difference.get("absentKeys").addAll(aggregationInfo.get("absentKeys"));
                    difference.get("diffValues").addAll(aggregationInfo.get("diffValues"));
                    clusterDifference.put(keyForPartitionRegionType, difference);
                }
            }
        }

        taskResults.clear();
    }

    System.out.println("____________________________");
    System.out.println("difference: ");
    System.out.println(clusterDifference);
    executorService.shutdown();
    adminDs.disconnect();
}

From source file:org.jactr.core.module.declarative.four.learning.DefaultDeclarativeLearningModule4.java

public DefaultDeclarativeLearningModule4() {
    super("DeclarativeLearningV4");

    _modelListener = new ModelListenerAdaptor() {

        @Override//from  w  w  w.j av a  2s.  co m
        public void moduleInstalled(ModelEvent event) {
            tryToAttach();
        }

        @Override
        public void cycleStarted(ModelEvent event) {
            /*
             * we don't need this code to do anything. it will be executed after all
             * the other tasks have been, i.e., all learning is done. if
             * getExecutor() returns the inline, nothing changes
             */
            FutureTask<Object> blockingTask = new FutureTask<Object>(new Runnable() {

                public void run() {
                    // noop once completed, object will be available
                }
            }, new Object());

            getExecutor().execute(blockingTask);

            try {
                blockingTask.get();
            } catch (Exception e) {
                LOGGER.error("Could not block while waiting for learning to finish ", e);
            }
        }
    };
}

From source file:ubic.gemma.loader.util.fetcher.HttpFetcher.java

/**
 * @param future//from w ww.  j  a v a 2s . c o  m
 * @param seekFile
 * @param outputFileName
 * @return
 */
protected Collection<LocalFile> doTask(FutureTask<Boolean> future, String seekFile, String outputFileName) {
    Executors.newSingleThreadExecutor().execute(future);
    try {

        while (!future.isDone()) {
            try {
                Thread.sleep(INFO_UPDATE_INTERVAL);
            } catch (InterruptedException ie) {

            }
            log.info((new File(outputFileName).length() + " bytes read"));
        }
        if (future.get().booleanValue()) {
            return listFiles(seekFile, outputFileName);
        }
    } catch (ExecutionException e) {
        throw new RuntimeException("Couldn't fetch file for " + seekFile, e);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted: Couldn't fetch file for " + seekFile, e);
    } catch (IOException e) {
        throw new RuntimeException("Couldn't fetch file for " + seekFile, e);
    }
    throw new RuntimeException("Couldn't fetch file for " + seekFile);
}

From source file:ubic.gemma.core.loader.util.fetcher.FtpArchiveFetcher.java

@Override
protected Collection<LocalFile> doTask(FutureTask<Boolean> future, long expectedSize, String seekFileName,
        String outputFileName) {/*from  www .j a v a2 s. c  om*/
    Executors.newSingleThreadExecutor().execute(future);
    try {
        File outputFile = new File(outputFileName);
        boolean ok = this.waitForDownload(future, expectedSize, outputFile);

        if (!ok) {
            // probably cancelled.
            return null;
        } else if (future.get()) {
            AbstractFetcher.log.info("Unpacking " + outputFile);
            this.unPack(outputFile);
            this.cleanUp(outputFile);
            if (outputFile.isDirectory())
                return this.listFiles(seekFileName, outputFile, null);

            return this.listFiles(seekFileName, outputFile.getParentFile(), null);
        }
    } catch (ExecutionException e) {
        future.cancel(true);
        throw new RuntimeException(
                "Couldn't fetch " + seekFileName + " from " + this.getNetDataSourceUtil().getHost(), e);
    } catch (InterruptedException e) {
        future.cancel(true);
        throw new RuntimeException("Interrupted: Couldn't fetch " + seekFileName + " from "
                + this.getNetDataSourceUtil().getHost(), e);
    } catch (IOException e) {
        future.cancel(true);
        throw new RuntimeException("IOException: Couldn't fetch " + seekFileName + " from "
                + this.getNetDataSourceUtil().getHost(), e);
    }
    future.cancel(true);
    throw new RuntimeException(
            "Couldn't fetch " + seekFileName + " from " + this.getNetDataSourceUtil().getHost());
}

From source file:ubic.gemma.loader.util.fetcher.FtpArchiveFetcher.java

@Override
protected Collection<LocalFile> doTask(FutureTask<Boolean> future, long expectedSize, String seekFileName,
        String outputFileName) {/*w  ww  .  jav a  2 s .  c o  m*/
    Executors.newSingleThreadExecutor().execute(future);
    try {
        File outputFile = new File(outputFileName);
        boolean ok = waitForDownload(future, expectedSize, outputFile);

        if (!ok) {
            // probably cancelled.
            return null;
        } else if (future.get().booleanValue()) {
            log.info("Unpacking " + outputFile);
            unPack(outputFile);
            cleanUp(outputFile);
            if (outputFile.isDirectory())
                return listFiles(seekFileName, outputFile, null);

            return listFiles(seekFileName, outputFile.getParentFile(), null);
        }
    } catch (ExecutionException e) {
        future.cancel(true);
        throw new RuntimeException(
                "Couldn't fetch " + seekFileName + " from " + this.getNetDataSourceUtil().getHost(), e);
    } catch (InterruptedException e) {
        future.cancel(true);
        throw new RuntimeException("Interrupted: Couldn't fetch " + seekFileName + " from "
                + this.getNetDataSourceUtil().getHost(), e);
    } catch (IOException e) {
        future.cancel(true);
        throw new RuntimeException("IOException: Couldn't fetch " + seekFileName + " from "
                + this.getNetDataSourceUtil().getHost(), e);
    }
    future.cancel(true);
    throw new RuntimeException(
            "Couldn't fetch " + seekFileName + " from " + this.getNetDataSourceUtil().getHost());
}