Search in sources :

Example 46 with FutureTask

use of java.util.concurrent.FutureTask in project dubbo by alibaba.

the class RpcContext method asyncCall.

/**
 * Async invocation. Timeout will be handled even if <code>Future.get()</code> is not called.
 *
 * @param callable
 * @return get the return result from <code>future.get()</code>
 */
@SuppressWarnings("unchecked")
public <T> Future<T> asyncCall(Callable<T> callable) {
    try {
        try {
            setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString());
            final T o = callable.call();
            // local invoke will return directly
            if (o != null) {
                FutureTask<T> f = new FutureTask<T>(new Callable<T>() {

                    public T call() throws Exception {
                        return o;
                    }
                });
                f.run();
                return f;
            } else {
            }
        } catch (Exception e) {
            throw new RpcException(e);
        } finally {
            removeAttachment(Constants.ASYNC_KEY);
        }
    } catch (final RpcException e) {
        return new Future<T>() {

            public boolean cancel(boolean mayInterruptIfRunning) {
                return false;
            }

            public boolean isCancelled() {
                return false;
            }

            public boolean isDone() {
                return true;
            }

            public T get() throws InterruptedException, ExecutionException {
                throw new ExecutionException(e.getCause());
            }

            public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                return get();
            }
        };
    }
    return ((Future<T>) getContext().getFuture());
}
Also used : TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) FutureTask(java.util.concurrent.FutureTask) TimeUnit(java.util.concurrent.TimeUnit) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 47 with FutureTask

use of java.util.concurrent.FutureTask in project opennms by OpenNMS.

the class KarafTestCase method executeCommand.

/**
 * Executes a shell command and returns output as a String.
 * Commands have a default timeout of 10 seconds.
 *
 * @param command
 * @return
 */
protected String executeCommand(final String command) {
    try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final PrintStream printStream = new PrintStream(byteArrayOutputStream);
        final PrintStream errStream = new PrintStream(byteArrayOutputStream)) {
        final ExecutorService executor = Executors.newCachedThreadPool();
        Subject subject = new Subject();
        subject.getPrincipals().add(new RolePrincipal("admin"));
        return Subject.doAs(subject, new PrivilegedExceptionAction<String>() {

            @Override
            public String run() throws Exception {
                final Session session = sessionFactory.create(System.in, printStream, errStream);
                LOG.info("Command: {}", command);
                FutureTask<String> commandFuture = new FutureTask<String>(new Callable<String>() {

                    public String call() {
                        try {
                            session.execute(command);
                        } catch (Exception e) {
                            e.printStackTrace(System.err);
                        }
                        printStream.flush();
                        errStream.flush();
                        return byteArrayOutputStream.toString();
                    }
                });
                try {
                    executor.submit(commandFuture);
                    String response = commandFuture.get(10, TimeUnit.SECONDS);
                    LOG.info("Response: {}", response);
                    return response;
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                    return "SHELL COMMAND TIMED OUT: " + command;
                }
            }
        });
    } catch (Exception e) {
        LOG.error("Error while executing command", e);
        throw new RuntimeException(e);
    }
}
Also used : PrintStream(java.io.PrintStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Subject(javax.security.auth.Subject) IOException(java.io.IOException) Callable(java.util.concurrent.Callable) FutureTask(java.util.concurrent.FutureTask) ExecutorService(java.util.concurrent.ExecutorService) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Session(org.apache.karaf.shell.api.console.Session)

Example 48 with FutureTask

use of java.util.concurrent.FutureTask in project android_frameworks_base by AOSPA.

the class ViewDebug method callMethodOnAppropriateTheadBlocking.

private static Object callMethodOnAppropriateTheadBlocking(final Method method, final Object object) throws IllegalAccessException, InvocationTargetException, TimeoutException {
    if (!(object instanceof View)) {
        return method.invoke(object, (Object[]) null);
    }
    final View view = (View) object;
    Callable<Object> callable = new Callable<Object>() {

        @Override
        public Object call() throws IllegalAccessException, InvocationTargetException {
            return method.invoke(view, (Object[]) null);
        }
    };
    FutureTask<Object> future = new FutureTask<Object>(callable);
    // Try to use the handler provided by the view
    Handler handler = view.getHandler();
    // Fall back on using the main thread
    if (handler == null) {
        handler = new Handler(android.os.Looper.getMainLooper());
    }
    handler.post(future);
    while (true) {
        try {
            return future.get(CAPTURE_TIMEOUT, java.util.concurrent.TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            Throwable t = e.getCause();
            if (t instanceof IllegalAccessException) {
                throw (IllegalAccessException) t;
            }
            if (t instanceof InvocationTargetException) {
                throw (InvocationTargetException) t;
            }
            throw new RuntimeException("Unexpected exception", t);
        } catch (InterruptedException e) {
        // Call get again
        } catch (CancellationException e) {
            throw new RuntimeException("Unexpected cancellation exception", e);
        }
    }
}
Also used : Handler(android.os.Handler) Callable(java.util.concurrent.Callable) InvocationTargetException(java.lang.reflect.InvocationTargetException) FutureTask(java.util.concurrent.FutureTask) CancellationException(java.util.concurrent.CancellationException) AccessibleObject(java.lang.reflect.AccessibleObject) ExecutionException(java.util.concurrent.ExecutionException)

Example 49 with FutureTask

use of java.util.concurrent.FutureTask in project ignite by apache.

the class GridMarshallerAbstractTest method unmarshal.

/**
 * @param buf Byte buffer to unmarshal.
 * @return Unmarshalled object.
 * @throws IgniteCheckedException Thrown if any exception occurs while unmarshalling.
 */
@SuppressWarnings({ "RedundantTypeArguments" })
protected static <T> T unmarshal(final byte[] buf) throws IgniteCheckedException {
    RunnableFuture<T> f = new FutureTask<>(new Callable<T>() {

        @Override
        public T call() throws IgniteCheckedException {
            return marsh.<T>unmarshal(buf, Thread.currentThread().getContextClassLoader());
        }
    });
    // Any deserialization has to be executed under a thread, that contains the Ignite instance name.
    new IgniteThread(igniteInstanceName, "unmarshal-thread", f).start();
    try {
        return f.get();
    } catch (Exception e) {
        if (e.getCause() instanceof IgniteCheckedException)
            throw (IgniteCheckedException) e.getCause();
        fail(e.getCause().getMessage());
    }
    return null;
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) FutureTask(java.util.concurrent.FutureTask) IgniteThread(org.apache.ignite.thread.IgniteThread) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IOException(java.io.IOException)

Example 50 with FutureTask

use of java.util.concurrent.FutureTask in project CzechIdMng by bcvsolutions.

the class DefaultSchedulerManagerIntegrationTest method testCreateAndRunSimpleTrigger.

@Test
public void testCreateAndRunSimpleTrigger() throws InterruptedException, ExecutionException {
    helper.setConfigurationValue(SchedulerConfiguration.PROPERTY_TASK_ASYNCHRONOUS_ENABLED, false);
    try {
        String result = "TEST_SCHEDULER_TWO";
        Task task = createTask(result);
        // 
        manager.createTrigger(task.getId(), getSimpleTrigger(task));
        // 
        helper.waitForResult(getContinueFunction());
        // 
        List<FutureTask<?>> taskList = getFutureTaskList(TestSchedulableTask.class);
        assertEquals(result, taskList.get(0).get());
        // 
        checkScheduledTask(task);
    } finally {
        helper.setConfigurationValue(SchedulerConfiguration.PROPERTY_TASK_ASYNCHRONOUS_ENABLED, true);
    }
}
Also used : FutureTask(java.util.concurrent.FutureTask) Task(eu.bcvsolutions.idm.core.scheduler.api.dto.Task) LongRunningFutureTask(eu.bcvsolutions.idm.core.scheduler.api.dto.LongRunningFutureTask) FutureTask(java.util.concurrent.FutureTask) LongRunningFutureTask(eu.bcvsolutions.idm.core.scheduler.api.dto.LongRunningFutureTask) AbstractIntegrationTest(eu.bcvsolutions.idm.test.api.AbstractIntegrationTest) Test(org.junit.Test)

Aggregations

FutureTask (java.util.concurrent.FutureTask)126 ExecutionException (java.util.concurrent.ExecutionException)44 Test (org.junit.Test)32 IOException (java.io.IOException)28 ExecutorService (java.util.concurrent.ExecutorService)23 Callable (java.util.concurrent.Callable)22 CountDownLatch (java.util.concurrent.CountDownLatch)20 TimeoutException (java.util.concurrent.TimeoutException)14 Handler (android.os.Handler)12 ArrayList (java.util.ArrayList)12 CancellationException (java.util.concurrent.CancellationException)10 InvocationTargetException (java.lang.reflect.InvocationTargetException)9 Future (java.util.concurrent.Future)8 AccessibleObject (java.lang.reflect.AccessibleObject)6 List (java.util.List)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 FileNotFoundException (java.io.FileNotFoundException)5 InputStream (java.io.InputStream)5 Iterator (java.util.Iterator)5 CancellationSignal (android.os.CancellationSignal)4