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());
}
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);
}
}
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);
}
}
}
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;
}
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);
}
}
Aggregations