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.eclipse.gyrex.jobs.internal.manager.JobManagerImpl.java

private <T> T executeWithRetry(final Callable<T> c) throws Exception {
    int attempt = 0;
    while (true) {
        try {/*  www .  ja  va2s.  c om*/
            return c.call();
        } catch (final ModificationConflictException e) {
            // try up to max retries
            if (++attempt > storageMaxNumberOfRetries)
                throw e;

            // wait a bit
            Thread.sleep(storageRetryDelayInMs);
        }
    }
}

From source file:org.callimachusproject.management.CalliServer.java

protected void submit(final Callable<Void> task) throws Exception {
    checkForErrors();/* w w w .  j av  a 2s  . c om*/
    executor.submit(new Runnable() {
        public void run() {
            begin();
            try {
                task.call();
            } catch (Exception exc) {
                saveError(exc);
            } finally {
                end();
            }
        }
    });
    Thread.yield();
}

From source file:org.cloudifysource.usm.launcher.DefaultProcessLauncher.java

private Process launchAsyncFromClosure(final Object arg) throws USMException {
    final Callable<?> closure = (Callable<?>) arg;
    Object retval;//from w  ww  .ja  v a 2  s  .  c  o m
    try {
        retval = closure.call();
    } catch (final Exception e) {
        logger.log(Level.SEVERE, "A closure entry failed to execute: " + e, e);
        throw new USMException("Launch of process from closure exited with an exception: " + e.getMessage(), e);
    }

    if (retval == null) {
        return null; // this is the expected behavior
    }

    if (retval instanceof Process) {
        return (Process) retval;
    }
    logger.warning("The Start closure returned a non-null value that is not a Process. "
            + "This value will be ignored! Returned value was of type: " + retval.getClass().getName()
            + ". Value was: " + retval);

    return null;
}

From source file:io.github.retz.web.ClientHelper.java

public static Optional<Job> getWholeFileWithTerminator(Client c, int id, String filename, boolean poll,
        OutputStream out, long offset, Callable<Boolean> terminator)
        throws IOException, JobNotFoundException, TimeoutException {
    Optional<Job> current;/*from  w w w.  j a v a 2s  .c  o  m*/

    {
        Response res = c.getJob(id);
        if (!(res instanceof GetJobResponse)) {
            LOG.error(res.status());
            throw new IOException(res.status());
        }
        GetJobResponse getJobResponse = (GetJobResponse) res;
        if (!getJobResponse.job().isPresent()) {
            throw new JobNotFoundException(id);
        }
    }

    int interval = INITAL_INTERVAL_MSEC;
    Job.JobState currentState = Job.JobState.QUEUED;

    long bytesRead = readFileUntilEmpty(c, id, filename, offset, out);
    offset = offset + bytesRead;

    do {
        Response res = c.getJob(id);
        if (!(res instanceof GetJobResponse)) {
            LOG.error(res.status());
            throw new IOException(res.status());
        }
        GetJobResponse getJobResponse = (GetJobResponse) res;
        current = getJobResponse.job();

        bytesRead = readFileUntilEmpty(c, id, filename, offset, out);
        offset = offset + bytesRead;

        if (current.isPresent()) {
            currentState = current.get().state();
            if ((currentState == Job.JobState.FINISHED || currentState == Job.JobState.KILLED)
                    && bytesRead == 0) {
                break;
            }
        }

        if (poll) {
            maybeSleep(interval);

            if (bytesRead == 0) {
                interval = Math.min(interval * 2, MAX_INTERVAL_MSEC);
            } else {
                interval = INITAL_INTERVAL_MSEC;
            }

            try {
                if (terminator != null && terminator.call()) {
                    throw new TimeoutException("Timeout at getWholeFile");
                }
            } catch (TimeoutException e) {
                throw e;
            } catch (Exception e) {
                LOG.error(e.toString(), e);
                return current; // I don't know how to handle it
            }
        } else {
            break;
        }
    } while (currentState != Job.JobState.FINISHED && currentState != Job.JobState.KILLED);

    if (!ClientHelper.fileExists(c, id, filename)) {
        // TODO: remove a file if it's already created
        throw new FileNotFoundException(filename);
    }

    return current;
}

From source file:org.codice.ddf.catalog.ui.metacard.MetacardApplication.java

private void tryUpdate(int retries, Callable<Boolean> func) throws IngestException, SourceUnavailableException {
    if (retries <= 0) {
        throw new IngestException("Could not update metacard!");
    }/* w w w  .  j av a 2 s  .  com*/
    LOGGER.trace("Trying to update metacard.");
    try {
        func.call();
        LOGGER.trace("Successfully updated metacard.");
    } catch (Exception e) {
        LOGGER.trace("Failed to update metacard");
        trySleep(350);
        tryUpdate(retries - 1, func);
    }
}

From source file:org.carrot2.workbench.core.ui.BenchmarkJob.java

/**
 * Create a set of benchmark threads./*from ww  w . ja  v  a2  s .co  m*/
 */
private Thread[] createBenchmarkThreads(final CountDownLatch latch, final MutableInt rounds,
        final IProgressMonitor monitor, final Callable<Long> benchmarkRunner) {
    final Thread[] pool = new Thread[settings.threads];
    for (int i = 0; i < settings.threads; i++) {
        final int threadID = i + 1;
        pool[i] = new Thread() {
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    final int totalRounds = settings.warmupRounds + settings.benchmarksRounds;
                    final int round;
                    synchronized (logWriter) {
                        round = rounds.intValue();
                        if (round == 0 || monitor.isCanceled()) {
                            // Exit if tests finished.
                            return;
                        }
                        rounds.decrement();
                    }

                    long time;
                    try {
                        time = benchmarkRunner.call();
                    } catch (Exception e) {
                        Utils.logError(e, false);
                        time = 0;
                    }

                    synchronized (logWriter) {
                        logWriter.format(Locale.ENGLISH, "%2d  %4d  %8.03f\n", threadID, totalRounds - round,
                                time / 1000d);

                        statistics = statistics.update((int) time);
                        monitor.worked(1);
                    }
                }
            }
        };
        pool[i].setName("benchmark-" + i);
        pool[i].setPriority(settings.priority.threadPriority);
        pool[i].start();
    }

    return pool;
}

From source file:ponzu.impl.test.Verify.java

/**
 * Runs the {@link Callable} {@code code} and asserts that it throws an {@code Exception} of the type
 * {@code expectedExceptionClass}.//from  w ww.  j a va  2 s  .  co  m
 * <p/>
 * {@code Callable} is most appropriate when a checked exception will be thrown.
 * If a subclass of {@link RuntimeException} will be thrown, the form
 * {@link #assertThrows(Class, Runnable)} may be more convenient.
 * <p/>
 * <p/>
 * e.g.
 * <pre>
 * Verify.<b>assertThrows</b>(StringIndexOutOfBoundsException.class, new Callable&lt;String&gt;()
 * {
 *    public String call() throws Exception
 *    {
 *        return "Craig".substring(42, 3);
 *    }
 * });
 * </pre>
 *
 * @see #assertThrows(Class, Runnable)
 */
public static void assertThrows(Class<? extends Exception> expectedExceptionClass, Callable<?> code) {
    try {
        code.call();
    } catch (Exception ex) {
        try {
            Assert.assertSame("Caught exception of type <" + ex.getClass().getName()
                    + ">, expected one of type <" + expectedExceptionClass.getName() + '>',
                    expectedExceptionClass, ex.getClass());
            return;
        } catch (AssertionError e) {
            throwMangledException(e);
        }
    }

    try {
        Assert.fail("Block did not throw an exception of type " + expectedExceptionClass.getName());
    } catch (AssertionError e) {
        throwMangledException(e);
    }
}

From source file:ponzu.impl.test.Verify.java

/**
 * Runs the {@link Callable} {@code code} and asserts that it throws an {@code Exception} of the type
 * {@code expectedExceptionClass}, which contains a cause of type expectedCauseClass.
 * <p/>/*from   www  . j av a  2 s . c  o  m*/
 * {@code Callable} is most appropriate when a checked exception will be thrown.
 * If a subclass of {@link RuntimeException} will be thrown, the form
 * {@link #assertThrowsWithCause(Class, Class, Runnable)} may be more convenient.
 * <p/>
 * <p/>
 * e.g.
 * <pre>
 * Verify.assertThrowsWithCause(RuntimeException.class, IOException.class, new Callable<Void>()
 * {
 *    public Void call() throws Exception
 *    {
 *        try
 *        {
 *            new File("").createNewFile();
 *        }
 *        catch (final IOException e)
 *        {
 *            throw new RuntimeException("Uh oh!", e);
 *        }
 *        return null;
 *    }
 * });
 * </pre>
 *
 * @see #assertThrowsWithCause(Class, Class, Runnable)
 */
public static void assertThrowsWithCause(Class<? extends Exception> expectedExceptionClass,
        Class<? extends Throwable> expectedCauseClass, Callable<?> code) {
    try {
        code.call();
    } catch (Exception ex) {
        try {
            Assert.assertSame("Caught exception of type <" + ex.getClass().getName()
                    + ">, expected one of type <" + expectedExceptionClass.getName() + '>',
                    expectedExceptionClass, ex.getClass());
            Throwable actualCauseClass = ex.getCause();
            Assert.assertNotNull("Caught exception with null cause, expected cause of type <"
                    + expectedCauseClass.getName() + '>', actualCauseClass);
            Assert.assertSame(
                    "Caught exception with cause of type<" + actualCauseClass.getClass().getName()
                            + ">, expected cause of type <" + expectedCauseClass.getName() + '>',
                    expectedCauseClass, actualCauseClass.getClass());
            return;
        } catch (AssertionError e) {
            throwMangledException(e);
        }
    }

    try {
        Assert.fail("Block did not throw an exception of type " + expectedExceptionClass.getName());
    } catch (AssertionError e) {
        throwMangledException(e);
    }
}

From source file:org.jasig.portal.portlet.rendering.worker.PortletExecutionWorker.java

@Override
public final void submit() {
    if (this.submitted > 0) {
        throw new IllegalStateException(this.getClass().getSimpleName() + " for " + this.getPortletWindowId()
                + " has already been submitted.");
    }//from ww w .j a  va 2  s .  co  m

    this.submitted = System.currentTimeMillis();

    try {
        //Run pre-submit interceptors
        for (final IPortletExecutionInterceptor interceptor : this.interceptors) {
            interceptor.preSubmit(request, response, this);
        }

        final Callable<V> callable = new PortletExecutionCallable<V>(this,
                new ExecutionLifecycleCallable<V>(new Callable<V>() {
                    @Override
                    public V call() throws Exception {
                        return callInternal();
                    }
                }));

        this.future = this.executorService.submit(callable);
    } catch (final Exception e) {
        //All is not well do the basic portlet execution lifecycle and then, return a Future that simply rethrows the exception

        final Callable<Future<V>> callable = new ExecutionLifecycleCallable<Future<V>>(
                new Callable<Future<V>>() {
                    @Override
                    public Future<V> call() throws Exception {
                        return Futures.immediateFailedFuture(e);
                    }
                });

        try {
            this.future = callable.call();
        } catch (Exception e1) {
            //We know this will never throw
        }
    }
}

From source file:com.haulmont.cuba.gui.WindowManager.java

protected Window createWindowByScreenClass(WindowInfo windowInfo, Map<String, Object> params) {
    Class screenClass = windowInfo.getScreenClass();

    Class[] paramTypes = ReflectionHelper.getParamTypes(params);
    Constructor constructor = null;
    try {//from w w w.  j a  v a 2 s  . c  o m
        constructor = screenClass.getConstructor(paramTypes);
    } catch (NoSuchMethodException e) {
        //
    }

    Object obj;
    try {
        if (constructor == null) {
            obj = screenClass.newInstance();
        } else {
            obj = constructor.newInstance(params);
        }
    } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
        throw new RuntimeException("Unable to instantiate window class", e);
    }

    if (obj instanceof Callable) {
        try {
            Callable callable = (Callable) obj;
            Window window = (Window) callable.call();
            return window;
        } catch (Exception e) {
            throw new RuntimeException("Unable to instantiate window class", e);
        }
    } else if (obj instanceof Runnable) {
        ((Runnable) obj).run();
        return null;
    } else
        throw new IllegalStateException("Screen class must be an instance of Callable<Window> or Runnable");
}