Java Code Examples for java.util.concurrent.FutureTask

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project PIE, under directory /R2/pie-runtime/src/main/java/com/pieframework/runtime/execution/.

Source file: CommandExec.java

  22 
vote

private Integer timedCall(Callable c,long timeout,TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
  FutureTask task=new FutureTask(c);
  this.executor.execute(task);
  int result=0;
  if (timeout == 0) {
    result=(Integer)task.get();
  }
 else {
    result=(Integer)task.get(timeout,timeUnit);
  }
  return result;
}
 

Example 2

From project Pitbull, under directory /pitbull-core/src/main/java/org/jboss/pitbull/internal/nio/socket/.

Source file: Worker.java

  22 
vote

public Future queueEvent(final Runnable runnable){
  FutureTask futureTask=new FutureTask(runnable,null);
synchronized (eventQueue) {
    eventQueue.add(futureTask);
    if (idle) {
      eventQueue.notify();
    }
 else {
      selector.wakeup();
    }
  }
  return futureTask;
}
 

Example 3

From project ServiceFramework, under directory /src/net/csdn/modules/transport/.

Source file: DefaultHttpTransportService.java

  21 
vote

public FutureTask<SResponse> asyncHttp(final Url url,final String jsonData,final RestRequest.Method method){
  FutureTask<SResponse> getRemoteDataTask=new FutureTask(new Callable<SResponse>(){
    @Override public SResponse call() throws Exception {
      return http(url,jsonData,method);
    }
  }
);
  threadPoolService.executor(ThreadPoolService.Names.SEARCH).execute(getRemoteDataTask);
  return getRemoteDataTask;
}
 

Example 4

From project siena, under directory /source/src/test/java/siena/base/test/.

Source file: BaseMultiThreadTest.java

  21 
vote

public void testMultiThreadSimple(){
  int count=0;
  while (count < 1000) {
    count++;
    logger.info("Launching " + count + "-th operation");
    final int c=count;
    FutureTask task=new FutureTask<Object>(new Thread(){
      public void run(){
        Model.getByKey(PersonLongAutoIDModel.class,PERSON_LONGAUTOID_TESLA.id);
        logger.info("Executed " + c + "-th operation");
      }
    }
,null);
    Thread thread=new Thread(task);
    thread.start();
    try {
      task.get(1l,TimeUnit.HOURS);
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
}
 

Example 5

From project jdonframework, under directory /src/com/jdon/async/future/.

Source file: EventResultFuture.java

  20 
vote

public EventResultFuture(String channel,final FutureListener messageListener,final DomainMessage domainMessage){
  this.channel=channel;
  this.messageListener=messageListener;
  this.domainMessage=domainMessage;
  this.futureTask=new FutureTask(new Callable<Boolean>(){
    public Boolean call() throws Exception {
      try {
        messageListener.action(domainMessage);
      }
 catch (      Exception e) {
        System.err.println("[JdonFramework]asynExecMessageListener() error" + e + " message="+ getChannel()+ " listener="+ messageListener.getClass().getName());
        return false;
      }
      return true;
    }
  }
);
}
 

Example 6

From project recommenders, under directory /plugins/org.eclipse.recommenders.rcp/src/org/eclipse/recommenders/internal/rcp/wiring/.

Source file: RecommendersModule.java

  20 
vote

private ActivePageFinder runUiFinder(){
  final ActivePageFinder finder=new ActivePageFinder();
  try {
    if (isRunningInUiThread()) {
      finder.call();
    }
 else {
      final FutureTask<IWorkbenchPage> task=new FutureTask(finder);
      Display.getDefault().asyncExec(task);
      task.get(2,TimeUnit.SECONDS);
    }
  }
 catch (  final Exception e) {
    RecommendersPlugin.logError(e,"Could not run 'active page finder' that early!");
  }
  return finder;
}
 

Example 7

From project AmDroid, under directory /AmDroid/src/main/java/com/jaeckel/amenoid/cwac/task/.

Source file: AsyncTaskEx.java

  19 
vote

/** 
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTaskEx(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return doInBackground(mParams);
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @Override protected void done(){
      Message message;
      Result result=null;
      try {
        result=get();
      }
 catch (      InterruptedException e) {
        com.jaeckel.amenoid.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        message=sHandler.obtainMessage(MESSAGE_POST_CANCEL,new AsyncTaskExResult<Result>(AsyncTaskEx.this,(Result[])null));
        message.sendToTarget();
        return;
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
      message=sHandler.obtainMessage(MESSAGE_POST_RESULT,new AsyncTaskExResult<Result>(AsyncTaskEx.this,result));
      message.sendToTarget();
    }
  }
;
}
 

Example 8

From project android-flip, under directory /FlipView/FlipLibrary/src/com/aphidmobile/utils/.

Source file: UI.java

  19 
vote

public static <T>T callInMainThread(Callable<T> call) throws Exception {
  if (isMainThread())   return call.call();
 else {
    FutureTask<T> task=new FutureTask<T>(call);
    getHandler().post(task);
    return task.get();
  }
}
 

Example 9

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/util/.

Source file: UserTask.java

  19 
vote

/** 
 * Creates a new user task. This constructor must be invoked on the UI thread.
 */
public UserTask(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return doInBackground(mParams);
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @Override protected void done(){
      Message message;
      Result result=null;
      try {
        result=get();
      }
 catch (      InterruptedException e) {
        android.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        message=sHandler.obtainMessage(MESSAGE_POST_CANCEL,new UserTaskResult<Result>(UserTask.this,(Result[])null));
        message.sendToTarget();
        return;
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
      message=sHandler.obtainMessage(MESSAGE_POST_RESULT,new UserTaskResult<Result>(UserTask.this,result));
      message.sendToTarget();
    }
  }
;
}
 

Example 10

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/app/.

Source file: AlbumDataLoader.java

  19 
vote

private <T>T executeAndWait(Callable<T> callable){
  FutureTask<T> task=new FutureTask<T>(callable);
  mMainHandler.sendMessage(mMainHandler.obtainMessage(MSG_RUN_OBJECT,task));
  try {
    return task.get();
  }
 catch (  InterruptedException e) {
    return null;
  }
catch (  ExecutionException e) {
    throw new RuntimeException(e);
  }
}
 

Example 11

From project apps-for-android, under directory /AnyCut/src/com/google/android/photostream/.

Source file: UserTask.java

  19 
vote

/** 
 * Creates a new user task. This constructor must be invoked on the UI thread.
 */
public UserTask(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return doInBackground(mParams);
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @Override protected void done(){
      Message message;
      Result result=null;
      try {
        result=get();
      }
 catch (      InterruptedException e) {
        android.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        message=sHandler.obtainMessage(MESSAGE_POST_CANCEL,new UserTaskResult<Result>(UserTask.this,(Result[])null));
        message.sendToTarget();
        return;
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
      message=sHandler.obtainMessage(MESSAGE_POST_RESULT,new UserTaskResult<Result>(UserTask.this,result));
      message.sendToTarget();
    }
  }
;
}
 

Example 12

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/client/execution/.

Source file: DefaultAssertionSynchronizer.java

  19 
vote

@Override public void finish(){
  AssertionHolder.finished();
  FutureTask<ResponsePayload> future=new FutureTask<ResponsePayload>(new PushAssertion());
  payloadFuture.set(future);
  executor.submit(future);
}
 

Example 13

From project aviator, under directory /src/main/java/com/googlecode/aviator/.

Source file: AviatorEvaluator.java

  19 
vote

/** 
 * Returns a compiled expression in cache
 * @param expression
 * @return
 */
public static Expression getCachedExpression(String expression){
  FutureTask<Expression> task=cacheExpressions.get(expression);
  if (task != null) {
    return getCompiledExpression(expression,task);
  }
 else   return null;
}
 

Example 14

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/event/.

Source file: EventManager.java

  19 
vote

/** 
 * Fire the specified event asynchronously.
 * @param < T > the result type
 * @param event the specified event
 * @return future result
 * @throws EventException event exception
 */
public <T>Future<T> fireEventAsynchronously(final Event<?> event) throws EventException {
  final ExecutorService executorService=Executors.newSingleThreadExecutor();
  final FutureTask<T> futureTask=new FutureTask<T>(new Callable<T>(){
    @Override public T call() throws Exception {
      synchronizedEventQueue.fireEvent(event);
      return null;
    }
  }
);
  executorService.execute(futureTask);
  return futureTask;
}
 

Example 15

From project capedwarf-blue, under directory /common/src/main/java/org/jboss/capedwarf/common/threads/.

Source file: ExecutorFactory.java

  19 
vote

/** 
 * Wrap callable into future task.
 * @param callable the callable
 * @return future task
 */
public static <T>Future<T> wrap(Callable<T> callable){
  final FutureTask<T> task=new FutureTask<T>(callable);
  final Executor executor=getInstance();
  executor.execute(task);
  return task;
}
 

Example 16

From project cloudify, under directory /restful/src/main/java/org/cloudifysource/rest/controllers/.

Source file: ServiceController.java

  19 
vote

/** 
 * undeploys the specified service of the specific application.
 * @param applicationName The application name.
 * @param serviceName The service name.
 * @return success status if service was undeployed successfully, else returns failure status.
 */
@JsonResponseExample(status="success",responseBody="{\"lifecycleEventContainerID\":\"bfae0a89-b5a0-4250-b393-6cedbf63ac76\"}") @PossibleResponseStatuses(codes={200,200},descriptions={"success","failed_to_locate_service"}) @RequestMapping(value="applications/{applicationName}/services/{serviceName}/timeout/{timeoutInMinutes}/undeploy",method=RequestMethod.DELETE) public @ResponseBody Map<String,Object> undeploy(@PathVariable final String applicationName,@PathVariable final String serviceName,@PathVariable final int timeoutInMinutes){
  final String absolutePuName=ServiceUtils.getAbsolutePUName(applicationName,serviceName);
  final ProcessingUnit processingUnit=admin.getProcessingUnits().waitFor(absolutePuName,PU_DISCOVERY_TIMEOUT_SEC,TimeUnit.SECONDS);
  if (processingUnit == null) {
    return unavailableServiceError(absolutePuName);
  }
  FutureTask<Boolean> undeployTask=new FutureTask<Boolean>(new Callable<Boolean>(){
    @Override public Boolean call() throws Exception {
      return processingUnit.undeployAndWait(timeoutInMinutes,TimeUnit.MINUTES);
    }
  }
);
  serviceUndeployExecutor.execute(undeployTask);
  final UUID lifecycleEventContainerID=startPollingForServiceUninstallLifecycleEvents(applicationName,serviceName,timeoutInMinutes,undeployTask);
  final Map<String,Object> returnMap=new HashMap<String,Object>();
  returnMap.put(CloudifyConstants.LIFECYCLE_EVENT_CONTAINER_ID,lifecycleEventContainerID);
  return successStatus(returnMap);
}
 

Example 17

From project cometd, under directory /cometd-javascript/common-test/src/main/java/org/cometd/javascript/.

Source file: JavaScriptThreadModel.java

  19 
vote

public void destroy() throws Exception {
  running=false;
  for (  FutureTask<Object> task : queue)   task.cancel(false);
  thread.interrupt();
  thread.join();
}
 

Example 18

From project core_4, under directory /impl/src/main/java/org/richfaces/skin/.

Source file: AbstractSkinFactory.java

  19 
vote

@Override public Skin getSkin(FacesContext context,String name){
  if (null == name) {
    throw new SkinNotFoundException(Messages.getMessage(Messages.NULL_SKIN_NAME_ERROR));
  }
  FutureTask<Skin> skinFuture=skins.get(name);
  if (skinFuture == null) {
    FutureTask<Skin> newSkinFuture=new FutureTask<Skin>(new SkinBuilder(name));
    skinFuture=skins.putIfAbsent(name,newSkinFuture);
    if (skinFuture == null) {
      skinFuture=newSkinFuture;
    }
  }
  try {
    skinFuture.run();
    return skinFuture.get();
  }
 catch (  InterruptedException e) {
    throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR,name),e);
  }
catch (  ExecutionException e) {
    throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR,name),e);
  }
}
 

Example 19

From project crash, under directory /shell/core/src/test/java/org/crsh/.

Source file: CommandQueue.java

  19 
vote

public synchronized Future<Runnable> executeAsync(){
  if (queue.size() == 0) {
    throw new AssertionFailedError();
  }
  Runnable runnable=queue.removeFirst();
  FutureTask<Runnable> future=new FutureTask<Runnable>(runnable,runnable);
  new Thread(future).start();
  return future;
}
 

Example 20

From project cxf-dosgi, under directory /systests/common/src/main/java/org/apache/cxf/dosgi/systests/common/.

Source file: AbstractListenerHookServiceListenerTest.java

  19 
vote

private void verifyGreeterResponse(FutureTask<Map<GreetingPhrase,String>> task,Object mutex) throws Exception {
  Map<GreetingPhrase,String> greetings=null;
synchronized (mutex) {
    while (task == null) {
      mutex.wait(500);
    }
    greetings=task.get();
  }
  assertEquals("Fred",greetings.get(new GreetingPhrase("Hello")));
}
 

Example 21

From project GenericKnimeNodes, under directory /com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/execution/.

Source file: AsynchronousToolExecutor.java

  19 
vote

/** 
 * C'tor.
 * @param executor The executor which should be handled asynchronously.
 */
public AsynchronousToolExecutor(final IToolExecutor executor){
  this.executor=executor;
  countdownLatch=new CountDownLatch(1);
  invokeAlreadyCalled=new AtomicBoolean(false);
  futureTask=new FutureTask<Integer>(new Callable<Integer>(){
    @Override public Integer call() throws Exception {
      return doCall();
    }
  }
);
}
 

Example 22

From project graph-collections, under directory /src/test/java/org/neo4j/collections/list/.

Source file: TestUnrolledLinkedListConcurrency.java

  19 
vote

@Test public void testAddInSamePageHavingReadPastWithoutReadTransaction() throws Exception {
  final ArrayList<Node> nodes=createNodes(4);
  final UnrolledLinkedList list=new UnrolledLinkedList(graphDb(),new IdComparator(),4);
  final StateSynchronizer sync=new StateSynchronizer(States.class);
  FutureTask<Boolean> reader=new ThrowingFutureTask<Boolean>(new Callable<Boolean>(){
    @Override public Boolean call() throws Exception {
      ArrayList<Node> innerNodes=new ArrayList<Node>(nodes.subList(0,3));
      Collections.reverse(innerNodes);
      assertTrue(sync.wait(States.READ));
      UnrolledLinkedList innerList=new UnrolledLinkedList(list.getBaseNode());
      int count=0;
      for (      Node node : innerList) {
        assertEquals(innerNodes.get(count),node);
        if (++count == 2) {
          assertTrue(sync.signalAndWait(States.WRITE,States.READ,1,TimeUnit.SECONDS));
        }
      }
      return true;
    }
  }
);
  executorService.execute(reader);
  int count=0;
  for (  Node node : nodes) {
    list.addNode(node);
    if (++count == 3) {
      restartTx();
      assertTrue(sync.signalAndWait(States.READ,States.WRITE));
    }
  }
  restartTx();
  sync.signal(States.READ);
  assertTrue(reader.get(1000,TimeUnit.MILLISECONDS));
}
 

Example 23

From project guice-jit-providers, under directory /extensions/service/src/com/google/inject/service/.

Source file: AsyncService.java

  19 
vote

public synchronized final Future<State> start(){
  Preconditions.checkState(state != State.STOPPED,"Cannot restart a service that has been stopped");
  if (state == State.STARTED) {
    return new FutureTask<State>(NOOP,State.STARTED);
  }
  return executor.submit(new Callable<State>(){
    public State call(){
      onStart();
      return state=State.STARTED;
    }
  }
);
}
 

Example 24

From project hdfs-nfs-proxy, under directory /src/main/java/com/cloudera/hadoop/hdfs/nfs/nfs4/.

Source file: AsyncTaskExecutor.java

  19 
vote

public AsyncTaskExecutor(){
  queue=new DelayQueue();
  executor=new ThreadPoolExecutor(10,500,5L,TimeUnit.SECONDS,queue,new ThreadFactoryBuilder().setDaemon(true).setNameFormat("AsyncTaskExecutor-" + instanceCounter.incrementAndGet() + "-%d").build()){
    protected <T>RunnableFuture<T> newTaskFor(    Runnable runnable,    T value){
      if (runnable instanceof DelayedRunnable) {
        return (FutureTask<T>)runnable;
      }
      return new FutureTask<T>(runnable,value);
    }
  }
;
}
 

Example 25

From project huahin-manager, under directory /src/main/java/org/huahinframework/manager/.

Source file: Runner.java

  19 
vote

/** 
 * @param war
 * @param port
 */
public void start(String war,int port){
  log.info("huahin-manager start");
  ConfigurableApplicationContext applicationContext=null;
  try {
    applicationContext=new ClassPathXmlApplicationContext("huahinManagerProperties.xml");
    Properties properties=(Properties)applicationContext.getBean("properties");
    QueueManager queueManager=new QueueManager(properties);
    RunnableFuture<Void> queueManagerThread=new FutureTask<Void>(queueManager);
    new Thread(queueManagerThread).start();
    SelectChannelConnector connector=new SelectChannelConnector();
    connector.setPort(port);
    Server server=new Server();
    server.setConnectors(new Connector[]{connector});
    WebAppContext web=new WebAppContext();
    web.setContextPath("/");
    web.setWar(war);
    server.addHandler(web);
    server.start();
    server.join();
    queueManagerThread.get();
  }
 catch (  Exception e) {
    log.error("huahin-manager aborted",e);
    System.exit(-1);
  }
 finally {
    if (applicationContext != null) {
      applicationContext.close();
    }
  }
  log.info("huahin-manager end");
}
 

Example 26

From project ImageLoader, under directory /core/src/main/java/com/novoda/imageloader/core/loader/util/.

Source file: AsyncTask.java

  19 
vote

/** 
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTask(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
      return doInBackground(mParams);
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @SuppressWarnings("unchecked") @Override protected void done(){
      Message message;
      Result result=null;
      try {
        result=get();
      }
 catch (      InterruptedException e) {
        android.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        message=sHandler.obtainMessage(MESSAGE_POST_CANCEL,new AsyncTaskResult<Result>(AsyncTask.this,(Result[])null));
        message.sendToTarget();
        return;
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
      message=sHandler.obtainMessage(MESSAGE_POST_RESULT,new AsyncTaskResult<Result>(AsyncTask.this,result));
      message.sendToTarget();
    }
  }
;
}
 

Example 27

From project karaf, under directory /itests/src/test/java/org/apache/karaf/itests/.

Source file: KarafTestSupport.java

  19 
vote

/** 
 * Executes a shell command and returns output as a String. Commands have a default timeout of 10 seconds.
 * @param command The command to execute.
 * @param timeout The amount of time in millis to wait for the command to execute.
 * @param silent  Specifies if the command should be displayed in the screen.
 * @return
 */
protected String executeCommand(final String command,final Long timeout,final Boolean silent){
  String response;
  final ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
  final PrintStream printStream=new PrintStream(byteArrayOutputStream);
  final CommandProcessor commandProcessor=getOsgiService(CommandProcessor.class);
  final CommandSession commandSession=commandProcessor.createSession(System.in,printStream,System.err);
  FutureTask<String> commandFuture=new FutureTask<String>(new Callable<String>(){
    public String call(){
      try {
        if (!silent) {
          System.err.println(command);
        }
        commandSession.execute(command);
      }
 catch (      Exception e) {
        e.printStackTrace(System.err);
      }
      printStream.flush();
      return byteArrayOutputStream.toString();
    }
  }
);
  try {
    executor.submit(commandFuture);
    response=commandFuture.get(timeout,TimeUnit.MILLISECONDS);
  }
 catch (  Exception e) {
    e.printStackTrace(System.err);
    response="SHELL COMMAND TIMED OUT: ";
  }
  return response;
}
 

Example 28

From project kernel_1, under directory /exo.kernel.component.cache/src/main/java/org/exoplatform/services/cache/impl/.

Source file: CacheServiceImpl.java

  19 
vote

public Collection<ExoCache<? extends Serializable,?>> getAllCacheInstances(){
  Collection<ExoCache<? extends Serializable,?>> caches=new ArrayList<ExoCache<? extends Serializable,?>>(cacheMap_.size());
  for (  FutureTask<ExoCache<? extends Serializable,?>> task : cacheMap_.values()) {
    ExoCache<? extends Serializable,?> cache=null;
    try {
      cache=task.get();
    }
 catch (    CancellationException e) {
      if (LOG.isTraceEnabled()) {
        LOG.trace("An exception occurred: " + e.getMessage());
      }
    }
catch (    InterruptedException e) {
      if (LOG.isTraceEnabled()) {
        LOG.trace("An exception occurred: " + e.getMessage());
      }
    }
catch (    ExecutionException e) {
      if (LOG.isTraceEnabled()) {
        LOG.trace("An exception occurred: " + e.getMessage());
      }
    }
    if (cache != null) {
      caches.add(cache);
    }
  }
  return caches;
}
 

Example 29

From project lastfm-android, under directory /app/src/fm/last/android/utils/.

Source file: UserTask.java

  19 
vote

/** 
 * Creates a new user task. This constructor must be invoked on the UI thread.
 */
public UserTask(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return doInBackground(mParams);
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @SuppressWarnings("unchecked") @Override protected void done(){
      Message message;
      Result result=null;
      try {
        result=get();
      }
 catch (      InterruptedException e) {
        android.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        message=sHandler.obtainMessage(MESSAGE_POST_CANCEL,new UserTaskResult<Result>(UserTask.this,(Result[])null));
        message.sendToTarget();
        return;
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
      message=sHandler.obtainMessage(MESSAGE_POST_RESULT,new UserTaskResult<Result>(UserTask.this,result));
      message.sendToTarget();
    }
  }
;
}
 

Example 30

From project liquidroid, under directory /src/liqui/droid/util/.

Source file: AsyncTask.java

  19 
vote

/** 
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTask(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      mTaskInvoked.set(true);
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return postResult(doInBackground(mParams));
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @Override protected void done(){
      try {
        final Result result=get();
        postResultIfNotInvoked(result);
      }
 catch (      InterruptedException e) {
        android.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        postResultIfNotInvoked(null);
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
    }
  }
;
}
 

Example 31

From project masa, under directory /plugins/masa-core/src/main/java/org/jvending/masa/ddmlib/.

Source file: AdbConnector.java

  19 
vote

public synchronized IDevice getFirstAttachedDevice() throws ShellCommandUnresponsiveException, ExecutionException {
  if (firstAttachedDevice != null) {
    return firstAttachedDevice;
  }
  FutureTask<Boolean> future=new FutureTask<Boolean>(new Callable<Boolean>(){
    public Boolean call(){
      while (!androidDebugBridge.hasInitialDeviceList()) {
        sleep(300);
      }
      firstAttachedDevice=androidDebugBridge.getDevices()[0];
      return true;
    }
  }
);
  execute(future);
  try {
    if (!future.get(5000,TimeUnit.MILLISECONDS)) {
      throw new ShellCommandUnresponsiveException();
    }
  }
 catch (  Exception e) {
    throw new ExecutionException("Failed to attach device",e);
  }
  return firstAttachedDevice;
}
 

Example 32

From project maven-surefire, under directory /maven-surefire-common/src/test/java/org/apache/maven/surefire/util/internal/.

Source file: TwoThreadBlockingQueueTest.java

  19 
vote

public void testPutAndTake() throws Exception {
  final FunkyTwoThreadBlockingQueue twoThreadBlockingQueue=new FunkyTwoThreadBlockingQueue();
  Callable<String> consumer=new Callable<String>(){
    public String call() throws Exception {
      int num=0;
      String taken;
      do {
        taken=twoThreadBlockingQueue.take();
        if (taken != TwoThreadBlockingQueue.poison) {
          Assert.assertEquals("item" + num++,taken);
        }
      }
 while (taken != TwoThreadBlockingQueue.poison);
      return taken;
    }
  }
;
  FutureTask<String> futureTask=new FutureTask<String>(consumer);
  Thread thread=new Thread(futureTask);
  thread.start();
  String[] items=generate(num);
  for (  String item : items) {
    twoThreadBlockingQueue.put(item);
  }
  twoThreadBlockingQueue.put(TwoThreadBlockingQueue.poison);
  futureTask.get();
  System.gc();
}
 

Example 33

From project Metamorphosis, under directory /metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/consumer/.

Source file: ConsumerZooKeeper.java

  19 
vote

public ZKLoadRebalanceListener getBrokerConnectionListener(final FetchManager fetchManager){
  final FutureTask<ZKLoadRebalanceListener> task=this.consumerLoadBalanceListeners.get(fetchManager);
  if (task != null) {
    try {
      return task.get();
    }
 catch (    final Exception e) {
      log.error("??ZKLoadRebalanceListener??",e);
      return null;
    }
  }
 else {
    return null;
  }
}
 

Example 34

From project mkgmap, under directory /src/uk/me/parabola/mkgmap/main/.

Source file: Preparer.java

  19 
vote

@SuppressWarnings("unchecked") protected <V>Future<V> addWorker(Callable<V> worker){
  if (threadPool == null) {
    FutureTask<V> future=new FutureTask<V>(worker);
    future.run();
    return future;
  }
 else {
    Future<Object> task=threadPool.submit((Callable<Object>)worker);
    remainingTasks.add(task);
    return (Future<V>)task;
  }
}
 

Example 35

From project moho, under directory /moho-common/src/main/java/com/voxeo/moho/common/event/.

Source file: EventDispatcher.java

  19 
vote

public void run(){
  while (true) {
    FutureTask<?> task=null;
synchronized (_queue) {
      task=_queue.poll();
      if (task == null) {
        processorRunning=false;
        break;
      }
    }
    try {
      task.run();
      task.get();
    }
 catch (    Throwable t) {
      LOG.info("Throwable when processing task.",t);
    }
  }
}
 

Example 36

From project multilane, under directory /src/main/java/com/m3/multilane/.

Source file: DefaultRendezvous.java

  19 
vote

@Override public Rendezvous start(Runnable runnable,final Integer timeoutMillis){
  if (runnable == null) {
    throw new IllegalArgumentException("The Runnable value should not be null.");
  }
  if (timeoutMillis == null) {
    throw new IllegalArgumentException("The timeout millis should not be null.");
  }
  final FutureTask<Void> task=new FutureTask<Void>(runnable,null);
  ForkJoinPoolProvider.getForkJoinPool().execute(task);
  futures.add(new VoidF0(){
    public void _(){
      try {
        task.get(timeoutMillis,TimeUnit.MILLISECONDS);
      }
 catch (      Throwable t) {
        onFailure(t);
      }
    }
  }
);
  return this;
}
 

Example 37

From project nodebox, under directory /src/main/java/nodebox/function/.

Source file: PythonLibrary.java

  19 
vote

private static Future<ImmutableMap<String,Function>> loadScript(final File file){
  FutureTask<ImmutableMap<String,Function>> task=new FutureTask<ImmutableMap<String,Function>>(new Callable<ImmutableMap<String,Function>>(){
    public ImmutableMap<String,Function> call() throws Exception {
      PythonUtils.initializePython();
      Py.getSystemState().path.append(new PyString(file.getParentFile().getCanonicalPath()));
      PythonInterpreter interpreter=new PythonInterpreter();
      try {
        interpreter.execfile(file.getCanonicalPath());
      }
 catch (      IOException e) {
        throw new LoadException(file,e);
      }
catch (      PyException e) {
        throw new LoadException(file,e);
      }
      PyStringMap map=(PyStringMap)interpreter.getLocals();
      ImmutableMap.Builder<String,Function> builder=ImmutableMap.builder();
      for (      Object key : map.keys()) {
        Object o=map.get(Py.java2py(key));
        if (o instanceof PyFunction) {
          String name=(String)key;
          Function f=new PythonFunction(name,(PyFunction)o);
          builder.put(name,f);
        }
      }
      return builder.build();
    }
  }
);
  Thread t=new Thread(task);
  t.start();
  return task;
}
 

Example 38

From project openengsb-framework, under directory /components/util/src/test/java/org/openengsb/core/util/.

Source file: OsgiServiceUtilsTest.java

  19 
vote

@Test public void testHandleParallelProxyCalls_shouldGetAnswersParallely() throws Exception {
  registerServiceViaId(new BlockingNullDomain(),"foo",NullDomain.class);
  final NullDomain service=utils.getOsgiServiceProxy(NullDomain.class);
  Callable<Object> normalCall=new Callable<Object>(){
    @Override public Object call() throws Exception {
      return service.nullMethod(42);
    }
  }
;
  Callable<Object> blockingCall=new Callable<Object>(){
    @Override public Object call() throws Exception {
      return service.nullMethod(42,"foo");
    }
  }
;
  FutureTask<Object> normalFuture=new FutureTask<Object>(normalCall);
  new Thread(normalFuture).start();
  FutureTask<Object> blockingFuture=new FutureTask<Object>(blockingCall);
  new Thread(blockingFuture).start();
  Object normalResult=normalFuture.get();
  assertThat((Integer)normalResult,is(42));
  try {
    blockingFuture.get(200,TimeUnit.MILLISECONDS);
    fail("blocking method returned premature");
  }
 catch (  TimeoutException e) {
  }
  sync.release();
  Object blockingResult=blockingFuture.get();
  assertThat((Integer)blockingResult,is(42));
}
 

Example 39

From project org.ops4j.pax.wicket, under directory /service/src/test/java/org/ops4j/pax/wicket/internal/.

Source file: MountTest.java

  19 
vote

@Test public void mountAndUnmountPageInSeparateThread() throws Exception {
  final DefaultPageMounter defaultPageMounter=new DefaultPageMounter("testapp",bundleContext);
  defaultPageMounter.addMountPoint("test",TestPage.class);
  final ServiceReference reference=mock(ServiceReference.class);
  when(bundleContext.getService(reference)).thenReturn(defaultPageMounter);
  final PageMounterTracker pageMounterTracker=new PageMounterTracker(bundleContext,wicketTester.getApplication(),"testapp");
  Callable<Void> mounterTask=new Callable<Void>(){
    public Void call() throws Exception {
      pageMounterTracker.addingService(reference);
      pageMounterTracker.removedService(reference,defaultPageMounter);
      return null;
    }
  }
;
  FutureTask<Void> futureTask=new FutureTask<Void>(mounterTask);
  new Thread(futureTask).start();
  futureTask.get();
}
 

Example 40

From project parasim, under directory /extensions/computation-execution-impl/src/main/java/org/sybila/parasim/execution/impl/.

Source file: SequentialExecution.java

  19 
vote

public SequentialExecution(final ComputationId computationId,final java.util.concurrent.Executor runnableExecutor,final Computation<L> computation,final Enrichment enrichment,final ContextEvent<ComputationInstanceContext> contextEvent,final Context parentContext){
  Validate.notNull(runnableExecutor);
  Validate.notNull(computation);
  Validate.notNull(enrichment);
  Validate.notNull(contextEvent);
  Validate.notNull(computationId);
  this.runnableExecutor=runnableExecutor;
  this.computation=computation;
  this.task=new FutureTask<>(createCallable(computation,contextEvent,parentContext,enrichment,computationId));
}
 

Example 41

From project platform_frameworks_ex, under directory /variablespeed/tests/src/com/android/ex/variablespeed/.

Source file: RealMediaPlayerTest.java

  19 
vote

@Override public MediaPlayerProxy createTestMediaPlayer() throws Exception {
  Callable<MediaPlayer> callable=new Callable<MediaPlayer>(){
    @Override public MediaPlayer call() throws Exception {
      return new MediaPlayer();
    }
  }
;
  FutureTask<MediaPlayer> future=new FutureTask<MediaPlayer>(callable);
  getInstrumentation().runOnMainSync(future);
  return DynamicProxy.dynamicProxy(MediaPlayerProxy.class,future.get(1,TimeUnit.SECONDS));
}
 

Example 42

From project platform_frameworks_support, under directory /v4/java/android/support/v4/content/.

Source file: ModernAsyncTask.java

  19 
vote

/** 
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public ModernAsyncTask(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      mTaskInvoked.set(true);
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return postResult(doInBackground(mParams));
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @Override protected void done(){
      try {
        final Result result=get();
        postResultIfNotInvoked(result);
      }
 catch (      InterruptedException e) {
        android.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        postResultIfNotInvoked(null);
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
    }
  }
;
}
 

Example 43

From project platform_packages_apps_contacts, under directory /tests/src/com/android/contacts/util/.

Source file: IntegrationTestUtils.java

  19 
vote

/** 
 * Execute a callable on the ui thread, returning its result synchronously. <p> Waits for an idle sync on the main thread (see  {@link Instrumentation#waitForIdle(Runnable)}) before executing this callable.
 */
public <T>T runOnUiThreadAndGetTheResult(Callable<T> callable) throws Throwable {
  FutureTask<T> future=new FutureTask<T>(callable);
  mInstrumentation.waitForIdle(future);
  try {
    return future.get();
  }
 catch (  ExecutionException e) {
    throw e.getCause();
  }
}
 

Example 44

From project platform_packages_apps_Gallery2_1, under directory /src/com/android/gallery3d/app/.

Source file: AlbumDataAdapter.java

  19 
vote

private <T>T executeAndWait(Callable<T> callable){
  FutureTask<T> task=new FutureTask<T>(callable);
  mMainHandler.sendMessage(mMainHandler.obtainMessage(MSG_RUN_OBJECT,task));
  try {
    return task.get();
  }
 catch (  InterruptedException e) {
    return null;
  }
catch (  ExecutionException e) {
    throw new RuntimeException(e);
  }
}
 

Example 45

From project Possom, under directory /search-command-control-spi/src/main/java/no/sesat/search/mode/executor/.

Source file: ParallelSearchCommandExecutor.java

  19 
vote

@Override public Map<Future<ResultList<ResultItem>>,SearchCommand> invokeAll(Collection<SearchCommand> callables) throws InterruptedException {
  if (LOG.isDebugEnabled()) {
    if (getExecutorService() instanceof ThreadPoolExecutor) {
      final ThreadPoolExecutor tpe=(ThreadPoolExecutor)getExecutorService();
      LOG.debug(DEBUG_POOL_COUNT + tpe.getActiveCount() + '/'+ tpe.getPoolSize());
      if (tpe instanceof ParallelSearchCommandExecutor.DebugThreadPoolExecutor) {
        final ParallelSearchCommandExecutor.DebugThreadPoolExecutor dtpe=(ParallelSearchCommandExecutor.DebugThreadPoolExecutor)tpe;
        LOG.debug("Still executing...");
synchronized (dtpe.EXECUTING) {
          for (          Runnable r : dtpe.EXECUTING) {
            try {
              LOG.debug(" " + ((FutureTask)r).get());
            }
 catch (            InterruptedException ex) {
              LOG.debug(ex);
            }
catch (            ExecutionException ex) {
              LOG.debug(ex);
            }
          }
        }
      }
    }
  }
  return super.invokeAll(callables);
}
 

Example 46

From project preon, under directory /preon-binding/src/main/java/org/codehaus/preon/util/.

Source file: LazyLoadingReference.java

  19 
vote

/** 
 * Returns an instance of  {@link T}, lazily constructed on demand using the  {@link #loader Loader}.
 * @return The referenced instance of {@link T}.
 * @throws InterruptedException When blocking call is interrupted.
 * @throws ExcecutionException  When the {@link Loader} threw an exception trying to load the data.
 */
public T get() throws InterruptedException, ExecutionException {
  while (true) {
    SoftReference<Future<T>> softReference=reference.get();
    boolean validSoftReference=true;
    if (softReference == null) {
      Callable<T> eval=new Callable<T>(){
        public T call() throws Exception {
          return loader.load();
        }
      }
;
      FutureTask<T> task=new FutureTask<T>(eval);
      softReference=new SoftReference<Future<T>>(task);
      if (validSoftReference=reference.compareAndSet(null,softReference)) {
        task.run();
      }
    }
    if (validSoftReference) {
      try {
        Future<T> future=softReference.get();
        if (future != null) {
          return future.get();
        }
 else {
          reference.compareAndSet(softReference,null);
        }
      }
 catch (      CancellationException e) {
        reference.compareAndSet(softReference,null);
      }
    }
  }
}
 

Example 47

From project rabbitmq-java-client, under directory /test/src/com/rabbitmq/client/test/.

Source file: ConfirmBase.java

  19 
vote

protected void waitForConfirms(final String testTitle) throws Exception {
  try {
    FutureTask<?> waiter=new FutureTask<Object>(new Runnable(){
      public void run(){
        try {
          channel.waitForConfirmsOrDie();
        }
 catch (        IOException e) {
          throw (ShutdownSignalException)e.getCause();
        }
catch (        InterruptedException _) {
          fail(testTitle + ": interrupted");
        }
      }
    }
,null);
    (Executors.newSingleThreadExecutor()).execute(waiter);
    waiter.get(10,TimeUnit.SECONDS);
  }
 catch (  ExecutionException ee) {
    Throwable t=ee.getCause();
    if (t instanceof ShutdownSignalException)     throw (ShutdownSignalException)t;
    if (t instanceof AssertionFailedError)     throw (AssertionFailedError)t;
    throw (Exception)t;
  }
catch (  TimeoutException _) {
    fail(testTitle + ": timeout");
  }
}
 

Example 48

From project riak-java-client, under directory /src/main/java/com/basho/riak/client/bucket/.

Source file: LazyBucketProperties.java

  19 
vote

/** 
 * @param client - a {@link RawClient} to be used to fetch the bucket properties
 * @param retrier - the {@link Retrier} to use
 * @param bucketName - Name of the Riak bucket 
 */
public LazyBucketProperties(final RawClient client,final Retrier retrier,final String bucket){
  future=new FutureTask<BucketProperties>(new Callable<BucketProperties>(){
    public BucketProperties call() throws Exception {
      return retrier.attempt(new Callable<BucketProperties>(){
        public BucketProperties call() throws Exception {
          return client.fetchBucket(bucket);
        }
      }
);
    }
  }
);
}
 

Example 49

From project scalaflavor4j, under directory /src/main/java/com/m3/scalaflavor4j/.

Source file: ConcurrentOps.java

  19 
vote

/** 
 * Evaluates an expression asynchronously, and returns a closure for retrieving the result.
 */
public static <R>F0<R> future(final Function0<R> p){
  final FutureTask<R> future=new FutureTask<R>(new Callable<R>(){
    public R call() throws Exception {
      return p.apply();
    }
  }
);
  forkJoinPool.execute(future);
  return new F0<R>(){
    public R _() throws InterruptedException, ExecutionException {
      return future.get();
    }
  }
;
}
 

Example 50

From project sisu-guice, under directory /extensions/service/src/com/google/inject/service/.

Source file: AsyncService.java

  19 
vote

public synchronized final Future<State> start(){
  Preconditions.checkState(state != State.STOPPED,"Cannot restart a service that has been stopped");
  if (state == State.STARTED) {
    return new FutureTask<State>(NOOP,State.STARTED);
  }
  return executor.submit(new Callable<State>(){
    public State call(){
      onStart();
      return state=State.STARTED;
    }
  }
);
}
 

Example 51

From project spring-batch-admin, under directory /spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/util/.

Source file: ThrottledTaskExecutor.java

  19 
vote

private Runnable doSubmit(final Runnable task){
  try {
    semaphore.acquire();
    count.incrementAndGet();
  }
 catch (  InterruptedException e) {
    Thread.currentThread().interrupt();
    throw new TaskRejectedException("Task could not be submitted because of a thread interruption.");
  }
  try {
    taskExecutor.execute(new FutureTask<Object>(task,null){
      @Override protected void done(){
        semaphore.release();
        count.decrementAndGet();
      }
    }
);
  }
 catch (  TaskRejectedException e) {
    semaphore.release();
    count.decrementAndGet();
    throw e;
  }
  return task;
}
 

Example 52

From project spring-js, under directory /src/test/java/org/springframework/context/annotation/.

Source file: SimpleConfigTests.java

  19 
vote

@Test public void testFooService() throws Exception {
  ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(getConfigLocations(),getClass());
  FooService fooService=ctx.getBean("fooServiceImpl",FooService.class);
  ServiceInvocationCounter serviceInvocationCounter=ctx.getBean("serviceInvocationCounter",ServiceInvocationCounter.class);
  String value=fooService.foo(1);
  assertEquals("bar",value);
  Future future=fooService.asyncFoo(1);
  assertTrue(future instanceof FutureTask);
  assertEquals("bar",future.get());
  assertEquals(2,serviceInvocationCounter.getCount());
  fooService.foo(1);
  assertEquals(3,serviceInvocationCounter.getCount());
}
 

Example 53

From project stilts, under directory /stomp-client/src/main/java/org/projectodd/stilts/stomp/client/.

Source file: ReceiptFuture.java

  19 
vote

ReceiptFuture(Callable<Void> receiptHandler){
  if (receiptHandler == null) {
    receiptHandler=NO_OP;
  }
  this.future=new FutureTask<Void>(receiptHandler);
}
 

Example 54

From project tesb-rt-se, under directory /job/controller/src/main/java/org/talend/esb/job/controller/internal/.

Source file: SimpleJobTask.java

  19 
vote

public SimpleJobTask(TalendJob job,String name){
  this.job=job;
  this.name=name;
  configuration=new Configuration();
  future=new FutureTask<Object>(new JobRunner(),null);
}
 

Example 55

From project TransFile, under directory /tests/net/sourceforge/transfile/network/.

Source file: BilateralConnectorTest.java

  19 
vote

@Test public void connect() throws InterruptedException, ExecutionException, ConnectException {
  try {
    final FutureTask<Connection> c2Task=new FutureTask<Connection>(new Callable<Connection>(){
      @Override public Connection call() throws Exception {
        return BilateralConnectorTest.this.connector2.connect();
      }
    }
);
    (new Thread(c2Task)).start();
    final Connection c1=this.connector1.connect();
    final Connection c2=c2Task.get();
    assertTrue(c1.isConnected());
    assertTrue(c2.isConnected());
  }
 catch (  final BilateralConnectException e) {
    fail("c1 failed:\n    outbound: " + e.getOutboundCause() + "\n    inbound: "+ e.getInboundCause());
  }
catch (  final ExecutionException e) {
    final Throwable cause=e.getCause();
    if (cause instanceof BilateralConnectException)     fail("c2 failed:\n    outbound: " + ((BilateralConnectException)cause).getOutboundCause() + "\n    inbound: "+ ((BilateralConnectException)cause).getInboundCause());
 else     throw e;
  }
}
 

Example 56

From project Ushahidi_Android, under directory /Libraries/abs/src/android/support/v4/content/.

Source file: ModernAsyncTask.java

  19 
vote

/** 
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public ModernAsyncTask(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      mTaskInvoked.set(true);
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return postResult(doInBackground(mParams));
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @Override protected void done(){
      try {
        final Result result=get();
        postResultIfNotInvoked(result);
      }
 catch (      InterruptedException e) {
        android.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        postResultIfNotInvoked(null);
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
    }
  }
;
}
 

Example 57

From project whirr, under directory /platforms/karaf/itests/src/test/java/org/apache/whirr/karaf/itest/.

Source file: WhirrKarafTestSupport.java

  19 
vote

/** 
 * Executes a shell command and returns output as a String. Commands have a default timeout of 10 seconds.
 * @param command The command to execute.
 * @param timeout The amount of time in millis to wait for the command to execute.
 * @param silent  Specifies if the command should be displayed in the screen.
 * @return
 */
protected String executeCommand(final String command,final Long timeout,final Boolean silent){
  String response;
  final ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
  final PrintStream printStream=new PrintStream(byteArrayOutputStream);
  final CommandProcessor commandProcessor=getOsgiService(CommandProcessor.class);
  final CommandSession commandSession=commandProcessor.createSession(System.in,printStream,System.err);
  FutureTask<String> commandFuture=new FutureTask<String>(new Callable<String>(){
    @Override public String call(){
      try {
        if (!silent) {
          System.err.println(command);
        }
        commandSession.execute(command);
      }
 catch (      Exception e) {
        e.printStackTrace(System.err);
      }
      printStream.flush();
      return byteArrayOutputStream.toString();
    }
  }
);
  try {
    executor.submit(commandFuture);
    response=commandFuture.get(timeout,TimeUnit.MILLISECONDS);
  }
 catch (  Exception e) {
    e.printStackTrace(System.err);
    response="SHELL COMMAND TIMED OUT: ";
  }
  return response;
}
 

Example 58

From project ws, under directory /exo.ws.rest.ext/src/main/java/org/exoplatform/services/rest/ext/groovy/.

Source file: DefaultGroovyResourceLoader.java

  19 
vote

protected URL getResource(final String filename) throws MalformedURLException {
  URL resource=resources.get(filename);
  if (resource != null && checkResource(resource)) {
    return resource;
  }
  Future<URL> findResourceURLTask=findResourceURLTasks.get(filename);
  if (findResourceURLTask == null) {
    FutureTask<URL> f=new FutureTask<URL>(new Callable<URL>(){
      public URL call() throws Exception {
        return findResourceURL(filename);
      }
    }
);
    findResourceURLTask=findResourceURLTasks.putIfAbsent(filename,f);
    if (findResourceURLTask == null) {
      findResourceURLTask=f;
      f.run();
    }
  }
  try {
    return findResourceURLTask.get();
  }
 catch (  CancellationException e) {
    if (LOG.isTraceEnabled()) {
      LOG.trace("An exception occurred: " + e.getMessage());
    }
  }
catch (  ExecutionException e) {
    throw (MalformedURLException)e.getCause();
  }
catch (  InterruptedException e) {
    Thread.currentThread().interrupt();
  }
 finally {
    findResourceURLTasks.remove(filename,findResourceURLTask);
  }
  return null;
}
 

Example 59

From project zen-project, under directory /zen-webservice/src/main/java/com/nominanuda/hyperapi/async/.

Source file: AbstractAsyncInvoker.java

  19 
vote

@SuppressWarnings("unchecked") public <T,Z>Z async(final Z delegee,final SuccessCallback<T> ss,final ErrorCallback ee){
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    final Object proxy,    final Method m,    final Object[] args) throws Throwable {
      Callable<T> task=new Callable<T>(){
        public T call() throws Exception {
          try {
            T res=(T)m.invoke(delegee,args);
            invokeSuccessCb(res,ss);
            return res;
          }
 catch (          InvocationTargetException e) {
            invokeErrorCb(ee,(Exception)e.getTargetException());
            return null;
          }
catch (          Exception e) {
            e.printStackTrace();
            throw e;
          }
        }
      }
;
      FutureTask<T> fut=new FutureTask<T>(task);
      executeFutureTask(fut);
      futures.add(fut);
      return null;
    }
  }
;
  Object proxy=Proxy.newProxyInstance(getClass().getClassLoader(),delegee.getClass().getInterfaces(),handler);
  return (Z)proxy;
}