use of java.util.concurrent.Callable in project android_frameworks_base by ParanoidAndroid.
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.Callable in project android by JetBrains.
the class GraphicsLayoutRenderer method render.
/**
* Render the layout to the passed {@link Graphics2D} instance using the defined viewport.
* <p/>
* <p/>Please note that this method is not thread safe so, if used from multiple threads, it's the caller's responsibility to synchronize
* the access to it.
*/
public boolean render(@NotNull final Graphics2D graphics) {
myRenderSessionLock.readLock().lock();
try {
if (!SystemInfo.isMac) {
// Do not enable anti-aliasing on MAC. It doesn't improve much and causes has performance issues when filling the background using
// alpha values.
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
myImageFactory.setGraphics(graphics);
AffineTransform oldTransform = graphics.getTransform();
if (myScale != 1.0) {
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
AffineTransform scaleTransform = new AffineTransform(oldTransform);
scaleTransform.scale(myScale, myScale);
graphics.setTransform(scaleTransform);
}
Result result = null;
try {
result = RenderService.runRenderAction(new Callable<Result>() {
@Override
public Result call() {
if (mySecurityManager != null) {
mySecurityManager.setActive(true, myCredential);
}
try {
return myRenderSession.render(RenderParams.DEFAULT_TIMEOUT, myInvalidate);
} finally {
if (mySecurityManager != null) {
mySecurityManager.setActive(false, myCredential);
}
}
}
});
} catch (Exception e) {
LOG.warn("Exception running render action", e);
}
if (myScale != 1.0) {
graphics.setTransform(oldTransform);
}
// access the system properties.
if (result != null && result.getStatus() != Result.Status.SUCCESS) {
//noinspection ThrowableResultOfMethodCallIgnored
if (result.getException() != null) {
LOG.warn(result.getException());
} else {
LOG.warn("Render error (no exception). Status=" + result.getStatus().name());
}
return false;
}
myInvalidate = false;
return true;
} finally {
myRenderSessionLock.readLock().unlock();
}
}
use of java.util.concurrent.Callable in project aries by apache.
the class ConfigurationTests method testConfiguration.
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testConfiguration() throws Exception {
Bundle tb3Bundle = installBundle("tb3.jar");
Configuration configurationA = null, configurationB = null;
try {
Filter filter = bundleContext.createFilter("(&(objectClass=" + CdiContainer.class.getName() + ")(service.bundleid=" + tb3Bundle.getBundleId() + "))");
ServiceTracker<CdiContainer, CdiContainer> containerTracker = new ServiceTracker<>(bundleContext, filter, null);
containerTracker.open();
containerTracker.waitForService(timeout);
ServiceReference<CdiContainer> serviceReference = containerTracker.getServiceReference();
assertNotNull(serviceReference);
assertEquals(CdiEvent.Type.WAITING_FOR_CONFIGURATIONS, serviceReference.getProperty(CdiConstants.CDI_CONTAINER_STATE));
configurationA = configurationAdmin.getConfiguration("configA", "?");
Dictionary<String, Object> properties = new Hashtable<>();
properties.put("ports", new int[] { 12, 4567 });
configurationA.update(properties);
configurationB = configurationAdmin.getConfiguration("configB", "?");
properties = new Hashtable<>();
properties.put("color", "green");
properties.put("ports", new int[] { 80 });
configurationB.update(properties);
containerTracker.close();
filter = bundleContext.createFilter("(&(objectClass=" + CdiContainer.class.getName() + ")(service.bundleid=" + tb3Bundle.getBundleId() + ")(" + CdiConstants.CDI_CONTAINER_STATE + "=CREATED))");
containerTracker = new ServiceTracker<>(bundleContext, filter, null);
containerTracker.open();
containerTracker.waitForService(timeout);
ServiceTracker<BeanService, BeanService> stA = new ServiceTracker<BeanService, BeanService>(bundleContext, bundleContext.createFilter("(&(objectClass=org.apache.aries.cdi.test.interfaces.BeanService)(bean=A))"), null);
stA.open(true);
BeanService<Callable<int[]>> beanService = stA.waitForService(timeout);
assertNotNull(beanService);
assertEquals("blue", beanService.doSomething());
assertArrayEquals(new int[] { 12, 4567 }, beanService.get().call());
ServiceTracker<BeanService, BeanService> stB = new ServiceTracker<BeanService, BeanService>(bundleContext, bundleContext.createFilter("(&(objectClass=org.apache.aries.cdi.test.interfaces.BeanService)(bean=B))"), null);
stB.open(true);
beanService = stB.waitForService(timeout);
assertNotNull(beanService);
assertEquals("green", beanService.doSomething());
assertArrayEquals(new int[] { 80 }, beanService.get().call());
} finally {
if (configurationA != null) {
try {
configurationA.delete();
} catch (Exception e) {
// ignore
}
}
if (configurationB != null) {
try {
configurationB.delete();
} catch (Exception e) {
// ignore
}
}
tb3Bundle.uninstall();
}
}
use of java.util.concurrent.Callable in project beam by apache.
the class BufferingStreamObserverTest method testThreadSafety.
@Test
public void testThreadSafety() throws Exception {
List<String> onNextValues = new ArrayList<>();
AdvancingPhaser phaser = new AdvancingPhaser(1);
final AtomicBoolean isCriticalSectionShared = new AtomicBoolean();
final BufferingStreamObserver<String> streamObserver = new BufferingStreamObserver<>(phaser, TestStreams.withOnNext(new Consumer<String>() {
@Override
public void accept(String t) {
// Use the atomic boolean to detect if multiple threads are in this
// critical section. Any thread that enters purposefully blocks by sleeping
// to increase the contention between threads artificially.
assertFalse(isCriticalSectionShared.getAndSet(true));
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
onNextValues.add(t);
assertTrue(isCriticalSectionShared.getAndSet(false));
}
}).build(), executor, 3);
List<String> prefixes = ImmutableList.of("0", "1", "2", "3", "4");
List<Callable<String>> tasks = new ArrayList<>();
for (String prefix : prefixes) {
tasks.add(new Callable<String>() {
@Override
public String call() throws Exception {
for (int i = 0; i < 10; i++) {
streamObserver.onNext(prefix + i);
}
return prefix;
}
});
}
List<Future<String>> results = executor.invokeAll(tasks);
for (Future<String> result : results) {
result.get();
}
streamObserver.onCompleted();
// Check that order was maintained.
int[] prefixesIndex = new int[prefixes.size()];
assertEquals(50, onNextValues.size());
for (String onNextValue : onNextValues) {
int prefix = Integer.parseInt(onNextValue.substring(0, 1));
int suffix = Integer.parseInt(onNextValue.substring(1, 2));
assertEquals(prefixesIndex[prefix], suffix);
prefixesIndex[prefix] += 1;
}
}
use of java.util.concurrent.Callable in project beam by apache.
the class BufferingStreamObserverTest method testIsReadyIsHonored.
@Test
public void testIsReadyIsHonored() throws Exception {
AdvancingPhaser phaser = new AdvancingPhaser(1);
final AtomicBoolean elementsAllowed = new AtomicBoolean();
final BufferingStreamObserver<String> streamObserver = new BufferingStreamObserver<>(phaser, TestStreams.withOnNext(new Consumer<String>() {
@Override
public void accept(String t) {
assertTrue(elementsAllowed.get());
}
}).withIsReady(elementsAllowed::get).build(), executor, 3);
// Start all the tasks
List<Future<String>> results = new ArrayList<>();
for (String prefix : ImmutableList.of("0", "1", "2", "3", "4")) {
results.add(executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
for (int i = 0; i < 10; i++) {
streamObserver.onNext(prefix + i);
}
return prefix;
}
}));
}
// Have them wait and then flip that we do allow elements and wake up those awaiting
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
elementsAllowed.set(true);
phaser.arrive();
for (Future<String> result : results) {
result.get();
}
streamObserver.onCompleted();
}
Aggregations