Example usage for java.util.concurrent Callable call

List of usage examples for java.util.concurrent Callable call

Introduction

In this page you can find the example usage for java.util.concurrent Callable call.

Prototype

V call() throws Exception;

Source Link

Document

Computes a result, or throws an exception if unable to do so.

Usage

From source file:ml.shifu.shifu.core.ModelRunner.java

/**
 * Run model to compute score for input NS Data map
 * //w w w  .  j ava2s . c o  m
 * @param rawDataNsMap
 *            - the original input, but key is wrapped by NSColumn
 * @return CaseScoreResult - model score
 */
public CaseScoreResult computeNsData(final Map<NSColumn, String> rawDataNsMap) {
    if (MapUtils.isEmpty(rawDataNsMap)) {
        return null;
    }

    CaseScoreResult scoreResult = new CaseScoreResult();

    if (this.scorer != null) {
        ScoreObject so = scorer.scoreNsData(rawDataNsMap);
        if (so == null) {
            return null;
        }

        scoreResult.setScores(so.getScores());
        scoreResult.setMaxScore(so.getMaxScore());
        scoreResult.setMinScore(so.getMinScore());
        scoreResult.setAvgScore(so.getMeanScore());
        scoreResult.setMedianScore(so.getMedianScore());
        scoreResult.setHiddenLayerScores(so.getHiddenLayerScores());
    }

    if (MapUtils.isNotEmpty(this.subScorers)) {
        if (this.isMultiThread && this.subScorers.size() > 1 && this.executorManager == null) {
            int threadPoolSize = Math.min(Runtime.getRuntime().availableProcessors(), this.subScorers.size());
            this.executorManager = new ExecutorManager<Pair<String, ScoreObject>>(threadPoolSize);
            // add a shutdown hook as a safe guard if some one not call close
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    ModelRunner.this.executorManager.forceShutDown();
                }
            }));
            log.info("MultiThread is enabled in ModelRunner, threadPoolSize = " + threadPoolSize);
        }

        List<Callable<Pair<String, ScoreObject>>> tasks = new ArrayList<Callable<Pair<String, ScoreObject>>>(
                this.subScorers.size());

        Iterator<Map.Entry<String, Scorer>> iterator = this.subScorers.entrySet().iterator();
        while (iterator.hasNext()) {
            final Map.Entry<String, Scorer> entry = iterator.next();

            Callable<Pair<String, ScoreObject>> callable = new Callable<Pair<String, ScoreObject>>() {
                @Override
                public Pair<String, ScoreObject> call() {
                    String modelName = entry.getKey();
                    Scorer subScorer = entry.getValue();
                    ScoreObject so = subScorer.scoreNsData(rawDataNsMap);
                    if (so != null) {
                        return Pair.of(modelName, so);
                    } else {
                        return null;
                    }
                }
            };

            tasks.add(callable);
        }

        if (this.isMultiThread && this.subScorers.size() > 1) {
            List<Pair<String, ScoreObject>> results = this.executorManager.submitTasksAndWaitResults(tasks);
            for (Pair<String, ScoreObject> result : results) {
                if (result != null) {
                    scoreResult.addSubModelScore(result.getLeft(), result.getRight());
                }
            }
        } else {
            for (Callable<Pair<String, ScoreObject>> task : tasks) {
                Pair<String, ScoreObject> result = null;
                try {
                    result = task.call();
                } catch (Exception e) {
                    // do nothing
                }
                if (result != null) {
                    scoreResult.addSubModelScore(result.getLeft(), result.getRight());
                }
            }
        }
    }

    return scoreResult;
}

From source file:com.grepcurl.random.BaseGenerator.java

public <T> T chooseOrCreateNew(Collection<T> elements, double oddsToCreateNew, Callable<T> createNewFunction)
        throws Exception {
    if (tryOdds(oddsToCreateNew)) {
        T t = createNewFunction.call();
        elements.add(t);//w ww.jav a2  s .  com
        return t;
    } else {
        return choose(elements);
    }
}

From source file:org.apache.ode.il.MockScheduler.java

public <T> T execTransaction(Callable<T> transaction, int timeout) throws Exception, ContextException {
    if (timeout > 0) {
        _txm.setTransactionTimeout(timeout);
    }//w  ww . ja  v  a2 s  . com
    beginTransaction();
    try {
        T retval = transaction.call();
        commitTransaction();
        return retval;
    } catch (Throwable t) {
        __log.error("Caught an exception during transaction", t);
        rollbackTransaction();
        throw new ContextException("Error in tx", t);
    } finally {
        if (timeout > 0) {
            // restores the default value
            _txm.setTransactionTimeout(0);
        }
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.SegmentDataStoreBlobGCIT.java

protected SegmentNodeStore getNodeStore(BlobStore blobStore) throws IOException {
    if (nodeStore == null) {
        FileStore.Builder builder = FileStore.builder(getWorkDir()).withBlobStore(blobStore)
                .withMaxFileSize(256).withCacheSize(64).withMemoryMapping(false);
        store = builder.build();//ww  w . j  a  v a 2 s .  co m
        CompactionStrategy compactionStrategy = new CompactionStrategy(false, true,
                CompactionStrategy.CleanupType.CLEAN_OLD, 0, CompactionStrategy.MEMORY_THRESHOLD_DEFAULT) {
            @Override
            public boolean compacted(@Nonnull Callable<Boolean> setHead) throws Exception {
                return setHead.call();
            }
        };
        compactionStrategy.setPersistCompactionMap(usePersistedMap);
        store.setCompactionStrategy(compactionStrategy);
        nodeStore = SegmentNodeStore.builder(store).build();
    }
    return nodeStore;
}

From source file:at.beris.virtualfile.client.ftp.FtpClient.java

private <T> T executionHandler(Callable<T> action) throws IOException {
    int connectionAttempts = MAX_CONNECTION_ATTEMPTS;
    while (connectionAttempts > 0) {
        try {//w  w w . j a v a2s  .  c o  m
            checkConnection();
            return action.call();
        } catch (FTPConnectionClosedException e) {
            LOGGER.debug("Exception", e);
            if (reconnect) {
                LOGGER.warn("Server closed connection. Reconnecting.");
                connectionAttempts--;
                connect();
            }
        } catch (IOException e) {
            LOGGER.debug("Exception", e);
            throw e;
        } catch (Exception e) {
            LOGGER.debug("Exception", e);
            throw new RuntimeException(e);
        }
    }
    return null;
}

From source file:com.atomicleopard.thundr.ftp.FtpSession.java

public <T> T timeLogAndCatch(String command, Callable<T> callable) {
    long start = System.currentTimeMillis();
    Environment env = ApiProxy.getCurrentEnvironment();
    Double origVal = (Double) env.getAttributes().put(FtpClient.API_DEADLINE_KEY, 60000.0);
    try {//  w w  w . j  a  v  a 2s .  c o  m
        Logger.info("Ftp %s", command);
        T result = callable.call();
        long end = System.currentTimeMillis();
        Logger.info("Ftp %s succeeded in %sms", command, (end - start));
        return result;
    } catch (Exception e) {
        long end = System.currentTimeMillis();
        Logger.warn("Ftp %s failed in %sms: %s", command, (end - start), e.getMessage());
        throw new FtpException(e, "Ftp failed - %s: %s", command, e.getMessage());
    } finally {
        if (origVal == null) {
            env.getAttributes().remove(FtpClient.API_DEADLINE_KEY);
        } else {
            env.getAttributes().put(FtpClient.API_DEADLINE_KEY, origVal);
        }
    }
}

From source file:com.aol.advertising.qiao.management.metrics.StatsCalculator.java

@Override
public void run() {

    for (Callable<?> c : statsCalcCallable.values()) {
        try {//from  ww w  .  java  2  s.co  m
            c.call();
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:org.redisson.spring.cache.RedissonCache.java

public <T> T get(Object key, Callable<T> valueLoader) {
    Object value = map.get(key);/*w  w  w  .  j  a  va 2  s  .  co  m*/
    if (value == null) {
        String lockName = getLockName(key);
        RLock lock = redisson.getLock(lockName);
        lock.lock();
        try {
            value = map.get(key);
            if (value == null) {
                try {
                    value = toStoreValue(valueLoader.call());
                } catch (Exception ex) {
                    try {
                        Class<?> c = Class.forName("org.springframework.cache.Cache$ValueRetrievalException");
                        Constructor<?> constructor = c.getConstructor(Object.class, Callable.class,
                                Throwable.class);
                        RuntimeException exception = (RuntimeException) constructor.newInstance(key,
                                valueLoader, ex.getCause());
                        throw exception;
                    } catch (Exception e) {
                        throw new IllegalStateException(e);
                    }
                }
                map.put(key, value);
            }
        } finally {
            lock.unlock();
        }
    }

    return (T) fromStoreValue(value);
}

From source file:org.eclipse.gyrex.cloud.services.zookeeper.ZooKeeperBasedService.java

/**
 * Executes the specified operation.//  w ww.j ava  2 s. c o  m
 * <p>
 * Note, the operation is executed regardless of the service
 * {@link #isClosed() closed state}. Clients should check
 * {@link #isClosed()}in the beginning of the operation.
 * </p>
 * 
 * @param operation
 *            the operation to execute
 * @return the result of the specified operation
 * @throws Exception
 *             if unable to compute a result
 */
protected <V> V execute(final Callable<V> operation) throws Exception {
    KeeperException exception = null;
    for (int i = 0; i < retryCount; i++) {
        try {
            return operation.call();
        } catch (final KeeperException.ConnectionLossException e) {
            if (exception == null) {
                exception = e;
            }
            if (CloudDebug.debug) {
                LOG.debug("Connection to the server has been lost (retry attempt {}).", i);
            }
            sleep(i);
        } catch (final KeeperException.SessionExpiredException e) {
            // we rely on connectionMonitor to close the service
            if (!isClosed()) {
                LOG.warn("ZooKeeper session expired. Service {} may be invalid now.", this);
            }
            // propagate this exception
            throw e;
        } catch (final GateDownException e) {
            // we rely on connectionMonitor to close the service
            if (!isClosed()) {
                LOG.warn("ZooKeeper gate is down. Service {} may be invalid now.", this);
            }
            // propagate this exception
            throw e;
        }
    }
    throw exception;
}

From source file:org.pentaho.di.repository.pur.PurRepository_GetObjectInformation_IT.java

private void testDeletedFlagForObject(Callable<RepositoryElementInterface> elementProvider) throws Exception {
    TransDelegate transDelegate = new TransDelegate(purRepository, unifiedRepository);
    JobDelegate jobDelegate = new JobDelegate(purRepository, unifiedRepository);
    FieldUtils.writeField(purRepository, "transDelegate", transDelegate, true);
    FieldUtils.writeField(purRepository, "jobDelegate", jobDelegate, true);

    RepositoryElementInterface element = elementProvider.call();
    RepositoryDirectoryInterface directory = purRepository
            .findDirectory(element.getRepositoryDirectory().getPath());
    element.setRepositoryDirectory(directory);

    purRepository.save(element, null, null);
    assertNotNull("Element was saved", element.getObjectId());

    RepositoryObject information;/*from w  ww.  j  a  va2s . c  o  m*/
    information = purRepository.getObjectInformation(element.getObjectId(), element.getRepositoryElementType());
    assertNotNull(information);
    assertFalse(information.isDeleted());

    purRepository.deleteTransformation(element.getObjectId());
    assertNotNull("Element was moved to Trash", unifiedRepository.getFileById(element.getObjectId().getId()));

    information = purRepository.getObjectInformation(element.getObjectId(), element.getRepositoryElementType());
    assertNotNull(information);
    assertTrue(information.isDeleted());
}