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:org.apache.solr.core.BlobRepository.java

private <T> BlobContentRef<T> getBlobIncRef(String key, Callable<BlobContent<T>> blobCreator) {
    BlobContent<T> aBlob;//w w w  .  j av  a 2s .c  o m
    if (this.coreContainer.isZooKeeperAware()) {
        synchronized (blobs) {
            aBlob = blobs.get(key);
            if (aBlob == null) {
                try {
                    aBlob = blobCreator.call();
                } catch (Exception e) {
                    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                            "Blob loading failed: " + e.getMessage(), e);
                }
            }
        }
    } else {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Blob loading is not supported in non-cloud mode");
        // todo
    }
    BlobContentRef<T> ref = new BlobContentRef<>(aBlob);
    synchronized (aBlob.references) {
        aBlob.references.add(ref);
    }
    return ref;
}

From source file:io.ecarf.core.cloud.task.processor.dictionary.AssembleDictionaryTask.java

@Override
public void run() throws IOException {

    log.info("Assembling dictionary, memory usage: " + Utils.getMemoryUsageInGB() + "GB");

    Stopwatch stopwatch = Stopwatch.createStarted();

    List<StorageObject> objects = this.cloudService.listCloudStorageObjects(bucket);

    //Set<String> files = new HashSet<>();

    List<Item> items = new ArrayList<>();

    for (StorageObject object : objects) {

        String filename = object.getName();

        if (filename.endsWith(FilenameUtils.KRYO_SERIALIZED_EXT)) {
            //files.add(filename);
            items.add(new Item(filename, object.getSize().longValue()));
        }//from w  ww. j  ava2s  . c  o m
    }

    log.info("Found " + items.size() + ", serialized files");

    int processors = Runtime.getRuntime().availableProcessors();

    BinPackingPartition function = new BinPackingPartition(items);
    function.setMaxBinItems((long) processors);
    List<Partition> partitions = function.partition();

    TermDictionary dictionary = TermDictionary.populateRDFOWLData(new TermDictionaryConcurrent());

    List<Callable<Void>> tasks = getSubTasks(partitions, dictionary);

    try {

        // check if we only have one file to process
        if (tasks.size() == 1) {

            tasks.get(0).call();

        } else if (processors == 1) {
            // only one process then process synchronously

            for (Callable<Void> task : tasks) {
                task.call();
            }

        } else {

            // multiple cores
            ExecutorService executor = Utils.createFixedThreadPool(processors);

            try {

                executor.invokeAll(tasks);

            } finally {
                executor.shutdown();
            }
        }

        tasks = null;

    } catch (Exception e) {
        log.error("Failed to process multiple files", e);
        throw new IOException(e);

    }

    int dicSize = dictionary.size();

    log.info("Successfully assembled dictionary with size: " + dicSize + ", max resourceId: "
            + dictionary.getLargestResourceId() + ", memory usage: " + Utils.getMemoryUsageInGB() + "GB"
            + ", timer: " + stopwatch);

    // extract the terms and encode the schema if needed
    if (StringUtils.isNotBlank(this.schemaFile) && StringUtils.isNotBlank(this.schemaBucket)) {
        this.encodeSchema(dictionary);
    }

    // encode the term stats file is needed
    if (StringUtils.isNotBlank(this.termStatsFile) && StringUtils.isNotBlank(this.encodedTermStatsFile)) {
        this.encodeTermsStats(dictionary);
    }

    // if no name provided for the dictionary file then create a default
    if (StringUtils.isBlank(this.dictionaryFile)) {
        this.dictionaryFile = this.cloudService.getInstanceId() + '_'
                + FilenameUtils.getSerializedGZipedDictionaryFilename();
    }

    this.dictionaryFile = FilenameUtils.getLocalFilePath(this.dictionaryFile);

    dictionary = ((ConcurrentDictionary) dictionary).getNonConcurrentDictionary();

    log.info("Successfully created non concurrent dictionary for serialization, memory usage: "
            + Utils.getMemoryUsageInGB() + "GB" + ", timer: " + stopwatch);

    dictionary.toFile(dictionaryFile, true);

    dictionary = null;

    log.info("Successfully serialized dictionary with size: " + dicSize + ", memory usage: "
            + Utils.getMemoryUsageInGB() + "GB" + ", timer: " + stopwatch);

    if (StringUtils.isBlank(this.targetBucket)) {
        this.targetBucket = bucket;
    }

    this.cloudService.uploadFileToCloudStorage(dictionaryFile, this.targetBucket);

    log.info("Successfully assembled, serialized and uploaded dictionary, memory usage: "
            + Utils.getMemoryUsageInGB() + "GB" + ", timer: " + stopwatch);

}

From source file:org.raml.yagi.framework.grammar.BaseGrammar.java

/**
 * Returns rule created by the callable that runs a new separate context.
 * @param callable The callable to execute in a new context
 * @param <T> The type of rule it returns
 * @return The rule//from  w w w .  ja  v a  2 s . co  m
 */
public <T extends Rule> T inNewContext(Callable<T> callable) {
    final GrammarContext oldContext = this.context;
    this.context = new GrammarContext();
    final T result;
    try {
        result = callable.call();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    this.context = oldContext;
    return result;
}

From source file:com.codeabovelab.dm.cluman.job.AbstractJobInstance.java

protected <T> T compareAndSetStatus(JobStatus expected, JobStatus status, Callable<T> ifOk) throws Exception {
    boolean result = this.statusRef.compareAndSet(expected, status);
    T res = null;//from w w w .j a  v  a 2 s  . c o m
    if (result) {
        SafeCloseable closeable = statusChanged(expected, status, null);
        if (ifOk != null) {
            res = ifOk.call();
        }
        closeable.close();
    }
    return res;
}

From source file:com.android.example.github.viewmodel.GithubViewModelFactory.java

@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
    Callable<? extends ViewModel> creator = creators.get(modelClass);
    if (creator == null) {
        for (Map.Entry<Class, Callable<? extends ViewModel>> entry : creators.entrySet()) {
            if (modelClass.isAssignableFrom(entry.getKey())) {
                creator = entry.getValue();
                break;
            }/*w  ww  .java  2  s . c  o  m*/
        }
    }
    if (creator == null) {
        throw new IllegalArgumentException("unknown model class " + modelClass);
    }
    try {
        return (T) creator.call();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.kuali.rice.krad.data.jpa.JpaPersistenceProvider.java

/**
 * Surrounds the transaction with a try/catch block that can use the {@link PersistenceExceptionTranslator} to
 * translate the exception if necessary.
 *
 * @param callable The data operation to invoke.
 * @param <T> The type of the data operation.
 *
 * @return The result from the data operation, if successful.
 *//*  w w w .  j a v a2  s. c o m*/
protected <T> T doWithExceptionTranslation(Callable<T> callable) {
    try {
        return callable.call();
    } catch (RuntimeException ex) {
        throw DataAccessUtils.translateIfNecessary(ex, this.persistenceExceptionTranslator);
    } catch (Exception ex) {
        // this should really never happen based on the internal usage in this class
        throw new RiceRuntimeException("Unexpected checked exception during data access.", ex);
    }
}

From source file:uk.co.unclealex.process.builder.BuildingProcessRequest.java

/**
 * Create a {@link Callable} that creates the command and executes it.
 * // ww w  .j a  va  2  s . co m
 * @return A {@link Callable} that creates the command and executes it.
 * @throws IOException
 */
protected Callable<ProcessResult> createExecutable() throws IOException {
    final String command = createCommand();
    final Callable<ProcessResult> task = execute(command, getProcessCallbacks(), getArguments(),
            getStandardInputSupplier());
    final Callable<ProcessResult> callable = new Callable<ProcessResult>() {
        @Override
        public ProcessResult call() throws Exception {
            try {
                return task.call();
            } finally {
                destroyCommand();
            }
        }
    };
    return callable;
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.BaseJpaDaoTest.java

/**
 * Executes the callback inside of a {@link JpaInterceptor} inside of a {@link TransactionCallback}
 *///from w ww  . j ava 2  s  .c  o  m
public final <T> T executeInTransaction(final Callable<T> callable) {
    return execute(new Callable<T>() {
        @Override
        public T call() throws Exception {
            return transactionOperations.execute(new TransactionCallback<T>() {
                @Override
                public T doInTransaction(TransactionStatus status) {
                    try {
                        return callable.call();
                    } catch (RuntimeException e) {
                        throw e;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    });
}

From source file:org.kuali.rice.kew.actions.ActionTakenEvent.java

/**
 * Wraps PostProcessor invocation with error handling
 * @param message log message/*from   www  . j  a v a 2 s .  c om*/
 * @param invocation the callable that invokes the postprocessor
 */
protected void invokePostProcessor(String message, Callable<ProcessDocReport> invocation) {
    if (!isRunPostProcessorLogic()) {
        return;
    }
    LOG.debug(message);
    try {
        ProcessDocReport report = invocation.call();
        if (!report.isSuccess()) {
            LOG.warn(report.getMessage(), report.getProcessException());
            throw new InvalidActionTakenException(report.getMessage());
        }
    } catch (Exception ex) {
        processPostProcessorException(ex);
    }
}

From source file:org.apache.hadoop.dynamodb.DynamoDBFibonacciRetryer.java

public <T> RetryResult<T> runWithRetry(Callable<T> callable, Reporter reporter, PrintCounter retryCounter) {
    fib1 = 0;//from w w w .j  av a 2 s. co m
    fib2 = 1;
    retryCount = 0;
    DateTime currentTime = new DateTime(DateTimeZone.UTC);
    DateTime retryEndTime = currentTime.plus(retryPeriod);

    while (true) {
        if (isShutdown) {
            log.info("Is shut down, giving up and returning null");
            return null;
        }

        try {
            T returnObj = callable.call();
            return new RetryResult<>(returnObj, retryCount);
        } catch (Exception e) {
            handleException(retryEndTime, e, reporter, retryCounter);
        }
    }
}