Java Code Examples for java.util.concurrent.Callable

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 aws-tasks, under directory /src/test/java/datameer/awstasks/aws/emr/.

Source file: AmazonElasticMapReduceCustomClientTest.java

  33 
vote

@Test @SuppressWarnings("unchecked") public void testDoWithRetry_ThrottleException() throws Exception {
  AmazonElasticMapReduceCustomClient client=new AmazonElasticMapReduceCustomClient("dummy","dummy");
  client.setRequestInterval(100);
  Callable callable=mock(Callable.class);
  AmazonServiceException exception=new AmazonServiceException("Rate exceeded");
  exception.setErrorCode("Throttling");
  exception.setStatusCode(400);
  when(callable.call()).thenThrow(exception,exception,exception).thenReturn(new Object());
  long startTime=System.currentTimeMillis();
  Object result=client.doThrottleSafe(callable);
  assertNotNull(result);
  assertThat((System.currentTimeMillis() - startTime),greaterThanOrEqualTo(3 * client.getRequestInterval()));
}
 

Example 2

From project clojure, under directory /src/jvm/clojure/lang/.

Source file: PersistentHashMap.java

  32 
vote

public Object fold(long n,final IFn combinef,final IFn reducef,IFn fjinvoke,final IFn fjtask,final IFn fjfork,final IFn fjjoin){
  Callable top=new Callable(){
    public Object call() throws Exception {
      Object ret=combinef.invoke();
      if (root != null)       ret=combinef.invoke(ret,root.fold(combinef,reducef,fjtask,fjfork,fjjoin));
      return hasNull ? combinef.invoke(ret,reducef.invoke(combinef.invoke(),null,nullValue)) : ret;
    }
  }
;
  return fjinvoke.invoke(top);
}
 

Example 3

From project adbcj, under directory /jdbc/src/main/java/org/adbcj/jdbc/.

Source file: JdbcConnectionManager.java

  29 
vote

public DbFuture<Connection> connect() throws DbException {
  if (isClosed()) {
    throw new DbException("This connection manager is closed");
  }
  final DbFutureConcurrentProxy<Connection> future=new DbFutureConcurrentProxy<Connection>();
  Future<Connection> executorFuture=executorService.submit(new Callable<Connection>(){
    public Connection call() throws Exception {
      try {
        java.sql.Connection jdbcConnection=DriverManager.getConnection(jdbcUrl,properties);
        JdbcConnection connection=new JdbcConnection(JdbcConnectionManager.this,jdbcConnection);
synchronized (lock) {
          if (isClosed()) {
            connection.close(true);
            future.setException(new DbException("Connection manager closed"));
          }
 else {
            connections.add(connection);
            future.setValue(connection);
          }
        }
        return connection;
      }
 catch (      SQLException e) {
        future.setException(new DbException(e));
        e.printStackTrace();
        throw e;
      }
 finally {
        future.setDone();
      }
    }
  }
);
  future.setFuture(executorFuture);
  return future;
}
 

Example 4

From project AdminCmd, under directory /src/main/java/be/Balor/Manager/Permissions/Plugins/.

Source file: SuperPermissions.java

  29 
vote

@Override public String getPermissionLimit(final Player p,final String limit){
  String result=null;
  if (mChat) {
    result=Reader.getInfo(p.getName(),InfoType.USER,p.getWorld().getName(),"admincmd." + limit);
  }
  if (result == null || (result != null && result.isEmpty())) {
    final Pattern regex=Pattern.compile("admincmd\\." + limit.toLowerCase() + "\\.[0-9]+");
    Set<PermissionAttachmentInfo> permissions=null;
    if (ACHelper.isMainThread()) {
      permissions=p.getEffectivePermissions();
    }
 else {
      final Callable<Set<PermissionAttachmentInfo>> perms=new Callable<Set<PermissionAttachmentInfo>>(){
        @Override public Set<PermissionAttachmentInfo> call() throws Exception {
          return p.getEffectivePermissions();
        }
      }
;
      final Future<Set<PermissionAttachmentInfo>> permTask=ACPluginManager.getScheduler().callSyncMethod(ACPluginManager.getCorePlugin(),perms);
      try {
        permissions=permTask.get();
        DebugLog.INSTANCE.info("Perms got for " + p.getName());
      }
 catch (      final InterruptedException e) {
        DebugLog.INSTANCE.info("Problem while gettings ASYNC perm of " + p.getName());
      }
catch (      final ExecutionException e) {
        DebugLog.INSTANCE.info("Problem while gettings ASYNC perm of " + p.getName());
      }
    }
    return permissionCheck(permissions,regex);
  }
 else {
    return result;
  }
}
 

Example 5

From project AeminiumRuntime, under directory /src/aeminium/runtime/implementations/implicitworkstealing/.

Source file: ImplicitWorkStealingRuntime.java

  29 
vote

@Override public <T>List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
  List<Future<T>> futures=new ArrayList<Future<T>>(tasks.size());
  for (  Callable<T> c : tasks) {
    futures.add(submit(c));
  }
  return futures;
}
 

Example 6

From project agraph-java-client, under directory /src/test/pool/.

Source file: AGConnPoolSessionTest.java

  29 
vote

@Test @Category(TestSuites.Stress.class) public void maxActive() throws Exception {
  final int seconds=5;
  final int clients=4;
  final AGConnPool pool=closeLater(AGConnPool.create(AGConnProp.serverUrl,AGAbstractTest.findServerUrl(),AGConnProp.username,AGAbstractTest.username(),AGConnProp.password,AGAbstractTest.password(),AGConnProp.catalog,"/",AGConnProp.repository,"pool.maxActive",AGConnProp.session,AGConnProp.Session.DEDICATED,AGConnProp.sessionLifetime,seconds * clients * 2,AGConnProp.httpSocketTimeout,TimeUnit.SECONDS.toMillis(seconds * clients),AGPoolProp.shutdownHook,true,AGPoolProp.testOnBorrow,true,AGPoolProp.maxActive,2,AGPoolProp.maxWait,TimeUnit.SECONDS.toMillis((seconds * clients) + 10),AGPoolProp.maxIdle,8));
  ExecutorService exec=Executors.newFixedThreadPool(clients);
  List<Future<Boolean>> errors=new ArrayList<Future<Boolean>>(clients);
  final AtomicLong idx=new AtomicLong(0);
  for (int i=0; i < clients; i++) {
    errors.add(exec.submit(new Callable<Boolean>(){
      @Override public Boolean call() throws Exception {
        try {
          long id=idx.incrementAndGet();
          log.debug(id + " start");
          AGRepositoryConnection conn=pool.borrowConnection();
          try {
            log.debug(id + " open");
            conn.size();
            Thread.sleep(TimeUnit.SECONDS.toMillis(seconds));
            conn.size();
          }
  finally {
            conn.close();
            log.debug(id + " close");
          }
          return true;
        }
 catch (        Throwable e) {
          log.error("error " + this,e);
          return false;
        }
      }
    }
));
  }
  assertSuccess(errors,seconds * clients * 2,TimeUnit.SECONDS);
}
 

Example 7

From project airlift, under directory /stats/src/main/java/io/airlift/stats/.

Source file: TimedStat.java

  29 
vote

public <T>T time(Callable<T> callable) throws Exception {
  long start=System.nanoTime();
  T result=callable.call();
  addValue(Duration.nanosSince(start));
  return result;
}
 

Example 8

From project akubra, under directory /akubra-rmi/src/main/java/org/akubraproject/rmi/server/.

Source file: ServerBlobCreator.java

  29 
vote

/** 
 * Creates a new ServerBlobCreator object.
 * @param con the server side blob store connection
 * @param estimatedSize the size estimate on the new blob from client
 * @param hints the blob creation hints from client
 * @param exporter the exporter to use
 * @throws IOException on an error in creation
 */
public ServerBlobCreator(final BlobStoreConnection con,final long estimatedSize,final Map<String,String> hints,Exporter exporter) throws IOException {
  super(exporter);
  out=new PipedOutputStream();
  final InputStream in=new PipedInputStream(out);
  readerService=Executors.newSingleThreadExecutor(new ThreadFactory(){
    public Thread newThread(    Runnable r){
      Thread t=new Thread(r,"akubra-rmi-blob-creator");
      t.setDaemon(true);
      return t;
    }
  }
);
  reader=readerService.submit(new Callable<RemoteBlob>(){
    public RemoteBlob call() throws Exception {
      if (log.isDebugEnabled())       log.debug("Started blob creator");
      return new ServerBlob(con.getBlob(in,estimatedSize,hints),getExporter());
    }
  }
);
  writerService=Executors.newSingleThreadExecutor(new ThreadFactory(){
    public Thread newThread(    Runnable r){
      Thread t=new Thread(r,"akubra-rmi-blob-writer");
      t.setDaemon(true);
      return t;
    }
  }
);
  if (log.isDebugEnabled())   log.debug("Server blob creator is ready");
}
 

Example 9

From project alfredo, under directory /alfredo/src/test/java/com/cloudera/alfredo/client/.

Source file: TestKerberosAuthenticator.java

  29 
vote

public void testAuthentication() throws Exception {
  setAuthenticationHandlerConfig(getAuthenticationHandlerConfiguration());
  KerberosTestUtils.doAsClient(new Callable<Void>(){
    @Override public Void call() throws Exception {
      _testAuthentication(new KerberosAuthenticator(),false);
      return null;
    }
  }
);
}
 

Example 10

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/taskcontrol/.

Source file: DefaultPrioritizedTask.java

  29 
vote

public DefaultPrioritizedTask(String name,Callable<? extends R> callable){
  wrappedCallable=callable;
  wrappedRunnable=null;
  priority=Integer.valueOf(Thread.NORM_PRIORITY);
  initResourceLocker(callable);
  setName(name);
}
 

Example 11

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

Source file: UI.java

  29 
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 12

From project android-rackspacecloud, under directory /extensions/httpnio/src/main/java/org/jclouds/http/pool/.

Source file: ConnectionPoolTransformingHttpCommandExecutorService.java

  29 
vote

/** 
 * This is an asynchronous operation that puts the <code>command</code> onto a queue. Later, it will be processed via the  {@link #invoke(HttpCommandRendezvous) invoke}method.
 */
public <T>ListenableFuture<T> submit(HttpCommand command,final Function<HttpResponse,T> responseTransformer){
  exceptionIfNotActive();
  final SynchronousQueue<?> channel=new SynchronousQueue<Object>();
  ListenableFuture<T> future=makeListenable(executorService.submit(new Callable<T>(){
    public T call() throws Exception {
      Object o=channel.take();
      if (o instanceof Exception) {
        throw (Exception)o;
      }
      return responseTransformer.apply((HttpResponse)o);
    }
  }
),executorService);
  HttpCommandRendezvous<T> rendezvous=new HttpCommandRendezvous<T>(command,channel,future);
  commandQueue.add(rendezvous);
  return rendezvous.getListenableFuture();
}
 

Example 13

From project android_external_guava, under directory /src/com/google/common/util/concurrent/.

Source file: Callables.java

  29 
vote

/** 
 * Creates a  {@code Callable} which immediately returns a preset value eachtime it is called.
 */
public static <T>Callable<T> returning(final @Nullable T value){
  return new Callable<T>(){
    public T call(){
      return value;
    }
  }
;
}
 

Example 14

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

Source file: AlbumDataLoader.java

  29 
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 15

From project arquillian-core, under directory /container/impl-base/src/main/java/org/jboss/arquillian/container/impl/client/container/.

Source file: ContainerDeployController.java

  29 
vote

public void deploy(@Observes final DeployDeployment event) throws Exception {
  executeOperation(new Callable<Void>(){
    @Inject private Event<DeployerEvent> deployEvent;
    @Inject @DeploymentScoped private InstanceProducer<DeploymentDescription> deploymentDescriptionProducer;
    @Inject @DeploymentScoped private InstanceProducer<Deployment> deploymentProducer;
    @Inject @DeploymentScoped private InstanceProducer<ProtocolMetaData> protocolMetadata;
    @Override public Void call() throws Exception {
      DeployableContainer<?> deployableContainer=event.getDeployableContainer();
      Deployment deployment=event.getDeployment();
      DeploymentDescription deploymentDescription=deployment.getDescription();
      deploymentDescriptionProducer.set(deploymentDescription);
      deploymentProducer.set(deployment);
      deployEvent.fire(new BeforeDeploy(deployableContainer,deploymentDescription));
      try {
        if (deploymentDescription.isArchiveDeployment()) {
          protocolMetadata.set(deployableContainer.deploy(deploymentDescription.getTestableArchive() != null ? deploymentDescription.getTestableArchive() : deploymentDescription.getArchive()));
        }
 else {
          deployableContainer.deploy(deploymentDescription.getDescriptor());
        }
        deployment.deployed();
      }
 catch (      Exception e) {
        deployment.deployedWithError(e);
        throw e;
      }
      deployEvent.fire(new AfterDeploy(deployableContainer,deploymentDescription));
      return null;
    }
  }
);
}
 

Example 16

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

Source file: EmulatorShutdown.java

  29 
vote

private void waitUntilShutDownIsComplete(final AndroidDevice device,final DeviceDisconnectDiscovery listener,ProcessExecutor executor,CountDownWatch countdown) throws AndroidExecutionException {
  try {
    boolean isOffline=executor.scheduleUntilTrue(new Callable<Boolean>(){
      @Override public Boolean call() throws Exception {
        return listener.isOffline();
      }
    }
,countdown.timeLeft(),countdown.getTimeUnit().convert(1,TimeUnit.SECONDS),countdown.getTimeUnit());
    if (isOffline == false) {
      throw new AndroidExecutionException("Unable to disconnect AVD device {0} in given timeout {1} seconds",device.getAvdName(),countdown.timeout());
    }
    log.log(Level.INFO,"Device {0} was disconnected in {1} seconds.",new Object[]{device.getAvdName(),countdown.timeElapsed()});
  }
 catch (  InterruptedException e) {
    throw new AndroidExecutionException(e,"Unable to disconnect AVD device {0}",device.getAvdName());
  }
catch (  ExecutionException e) {
    throw new AndroidExecutionException(e,"Unable to disconnect AVD device {0}",device.getAvdName());
  }
}
 

Example 17

From project arquillian_deprecated, under directory /impl-base/src/main/java/org/jboss/arquillian/impl/client/container/.

Source file: ContainerDeployController.java

  29 
vote

public void deploy(@Observes final DeployDeployment event) throws Exception {
  executeOperation(new Callable<Void>(){
    @Inject private Event<DeployerEvent> deployEvent;
    @Inject @DeploymentScoped private InstanceProducer<DeploymentDescription> deploymentDescription;
    @Inject @DeploymentScoped private InstanceProducer<ProtocolMetaData> protocolMetadata;
    @Override public Void call() throws Exception {
      DeployableContainer<?> deployableContainer=event.getDeployableContainer();
      DeploymentDescription deployment=event.getDeployment();
      deploymentDescription.set(deployment);
      deployEvent.fire(new BeforeDeploy(deployableContainer,deployment));
      if (deployment.isArchiveDeployment()) {
        protocolMetadata.set(deployableContainer.deploy(deployment.getTestableArchive() != null ? deployment.getTestableArchive() : deployment.getArchive()));
      }
 else {
        deployableContainer.deploy(deployment.getDescriptor());
      }
      deployEvent.fire(new AfterDeploy(deployableContainer,deployment));
      return null;
    }
  }
);
}
 

Example 18

From project astyanax, under directory /src/main/java/com/netflix/astyanax/recipes/reader/.

Source file: AllRowsReader.java

  29 
vote

/** 
 * Main execution block for the all rows query.  
 */
@Override public Boolean call() throws Exception {
  List<Callable<Boolean>> subtasks=Lists.newArrayList();
  if (this.concurrencyLevel != null) {
    List<TokenRange> tokens=partitioner.splitTokenRange(startToken == null ? partitioner.getMinToken() : startToken,endToken == null ? partitioner.getMinToken() : endToken,this.concurrencyLevel);
    for (    TokenRange range : tokens) {
      subtasks.add(makeTokenRangeTask(range.getStartToken(),range.getEndToken()));
    }
  }
 else {
    List<TokenRange> ranges=keyspace.describeRing();
    for (    TokenRange range : ranges) {
      subtasks.add(makeTokenRangeTask(partitioner.getTokenMinusOne(range.getStartToken()),range.getEndToken()));
    }
  }
  try {
    if (executor == null) {
      ExecutorService localExecutor=Executors.newFixedThreadPool(subtasks.size(),new ThreadFactoryBuilder().setDaemon(true).setNameFormat("AstyanaxAllRowsReader-%d").build());
      try {
        futures.addAll(startTasks(localExecutor,subtasks));
        return waitForTasksToFinish();
      }
  finally {
        localExecutor.shutdownNow();
      }
    }
 else {
      futures.addAll(startTasks(executor,subtasks));
      return waitForTasksToFinish();
    }
  }
 catch (  Throwable t) {
    LOG.warn("AllRowsReader terminated",t);
    cancel();
    return false;
  }
}
 

Example 19

From project atlas, under directory /src/main/java/com/ning/atlas/.

Source file: ActualDeployment.java

  29 
vote

private Future<Status> installAllOnHost(ListeningExecutorService es,final Host server,final List<Pair<Uri<Installer>,Installer>> installations){
  return es.submit(new Callable<Status>(){
    @Override public Status call() throws Exception {
      log.info("installing on %s : %s",server.getId(),installations);
      Status last_status=Status.okay();
      for (      Pair<Uri<Installer>,Installer> installation : installations) {
        log.info("installing %s on %s",installation.getKey().toString(),server.getId());
        bus.post(new StartServerInstall(server.getId(),installation.getLeft()));
        last_status=installation.getValue().install(server,installation.getKey(),ActualDeployment.this).get();
        bus.post(new FinishedServerInstall(server.getId(),installation.getLeft()));
      }
      return last_status;
    }
  }
);
}
 

Example 20

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

Source file: AviatorEvaluator.java

  29 
vote

/** 
 * Compile a text expression to Expression object
 * @param expression text expression
 * @param cached Whether to cache the compiled result,make true to cache it.
 * @return
 */
public static Expression compile(final String expression,boolean cached){
  if (expression == null || expression.trim().length() == 0) {
    throw new CompileExpressionErrorException("Blank expression");
  }
  if (cached) {
    FutureTask<Expression> task=cacheExpressions.get(expression);
    if (task != null) {
      return getCompiledExpression(expression,task);
    }
    task=new FutureTask<Expression>(new Callable<Expression>(){
      public Expression call() throws Exception {
        return innerCompile(expression);
      }
    }
);
    FutureTask<Expression> existedTask=cacheExpressions.putIfAbsent(expression,task);
    if (existedTask == null) {
      existedTask=task;
      existedTask.run();
    }
    return getCompiledExpression(expression,existedTask);
  }
 else {
    return innerCompile(expression);
  }
}
 

Example 21

From project awaitility, under directory /awaitility/src/main/java/com/jayway/awaitility/core/.

Source file: AbstractHamcrestCondition.java

  29 
vote

public AbstractHamcrestCondition(final Callable<T> supplier,final Matcher<? super T> matcher,ConditionSettings settings){
  if (supplier == null) {
    throw new IllegalArgumentException("You must specify a supplier (was null).");
  }
  if (matcher == null) {
    throw new IllegalArgumentException("You must specify a matcher (was null).");
  }
  Callable<Boolean> callable=new Callable<Boolean>(){
    public Boolean call() throws Exception {
      lastResult=supplier.call();
      return matcher.matches(lastResult);
    }
  }
;
  conditionAwaiter=new ConditionAwaiter(callable,settings){
    @Override protected String getTimeoutMessage(){
      return String.format("%s expected %s but was <%s>",getCallableDescription(supplier),HamcrestToStringFilter.filter(matcher),lastResult);
    }
  }
;
}
 

Example 22

From project azkaban, under directory /azkaban/src/unit/azkaban/utils/process/.

Source file: ProcessTest.java

  29 
vote

private Future<Object> runInSeperateThread(final ExecutorService executor,final AzkabanProcess process) throws InterruptedException {
  Future<Object> result=executor.submit(new Callable<Object>(){
    public Object call() throws IOException {
      process.run();
      return null;
    }
  }
);
  process.awaitStartup();
  return result;
}
 

Example 23

From project azure4j-blog-samples, under directory /SQLAzure/JDBCRetryPolicy/src/com/persistent/azure/jdbc/retry/.

Source file: RetryPolicy.java

  29 
vote

/** 
 * This constructor populates the transient error code list and initializes parameters
 * @param retryCount The number of times to retry the task
 * @param waitingTime The Time interval between tries
 * @param retriableTask The task that is to be retried in event of transient failure
 */
public RetryPolicy(int retryCount,long waitingTime,final Callable<T> retriableTask){
  populateErrorCodeList();
  this.retryCount=retryCount;
  this.retriesLeft=retryCount;
  this.waitingTime=waitingTime;
  this.retriableTask=retriableTask;
}
 

Example 24

From project b1-pack, under directory /standard/src/test/java/org/b1/pack/standard/common/.

Source file: SynchronousPipeTest.java

  29 
vote

@Test public void test_read_write() throws Exception {
  ExecutorService service=Executors.newCachedThreadPool();
  Future<Boolean> readerFuture=service.submit(new Callable<Boolean>(){
    @Override public Boolean call() throws Exception {
      byte[] buffer=new byte[1000];
      readerStarted=true;
      assertEquals(0,pipe.inputStream.read(buffer,5,0));
      assertFalse(writerStarted);
      assertEquals(2,pipe.inputStream.read(buffer,10,2));
      assertEquals("01",new String(buffer,10,2,Charsets.UTF_8));
      assertTrue(writerStarted);
      assertEquals(8,pipe.inputStream.read(buffer,1,10));
      assertEquals("23456789",new String(buffer,1,8,Charsets.UTF_8));
      assertFalse(writerClosed);
      assertEquals(-1,pipe.inputStream.read(buffer,1,10));
      assertTrue(writerClosed);
      return true;
    }
  }
);
  Thread.sleep(500);
  assertTrue(readerStarted);
  Future<Boolean> writerFuture=service.submit(new Callable<Boolean>(){
    @Override public Boolean call() throws Exception {
      writerStarted=true;
      pipe.outputStream.write(TEST_BYTES);
      Thread.sleep(500);
      pipe.outputStream.close();
      writerClosed=true;
      return true;
    }
  }
);
  assertTrue(readerFuture.get());
  assertTrue(writerFuture.get());
}
 

Example 25

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

Source file: EventManager.java

  29 
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 26

From project big-data-plugin, under directory /shims/cdh4/src/org/pentaho/hadoop/shim/cdh4/.

Source file: ClassPathModifyingSqoopShim.java

  29 
vote

/** 
 * Run a given  {@link Callable} within a code block that sets the {@code "java.class.path"} property to the path defined for the {@link HadoopConfigurationClassLoader}used to load this class, if it was used. If not, this is the same as calling  {@code callable.call()}.
 * @param callable Callable to execute with a modified class path set.
 * @return
 */
public int runWithModifiedClassPathProperty(Callable<Integer> callable){
  String newClassPath=getClassPathString();
  String originalClassPath=System.getProperty(PROPERTY_JAVA_CLASS_PATH);
  if (newClassPath != null) {
    System.setProperty(PROPERTY_JAVA_CLASS_PATH,newClassPath);
  }
  try {
    Integer returnVal=callable.call();
    return returnVal == null ? Integer.MIN_VALUE : returnVal.intValue();
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
 finally {
    if (originalClassPath != null) {
      System.setProperty(PROPERTY_JAVA_CLASS_PATH,originalClassPath);
    }
  }
}
 

Example 27

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.

Source file: AbstractServiceReferenceRecipe.java

  29 
vote

protected Object createProxy(final Callable<Object> dispatcher,Set<Class<?>> interfaces) throws Exception {
  if (!interfaces.iterator().hasNext()) {
    return new Object();
  }
 else {
    return BlueprintExtender.getProxyManager().createDelegatingProxy(blueprintContainer.getBundleContext().getBundle(),interfaces,dispatcher,null);
  }
}
 

Example 28

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: BoneCP.java

  29 
vote

/** 
 * Obtain a connection asynchronously by queueing a request to obtain a connection in a separate thread. Use as follows:<p> Future&lt;Connection&gt; result = pool.getAsyncConnection();<p> ... do something else in your application here ...<p> Connection connection = result.get(); // get the connection<p>
 * @return A Future task returning a connection.
 */
public ListenableFuture<Connection> getAsyncConnection(){
  return this.asyncExecutor.submit(new Callable<Connection>(){
    public Connection call() throws Exception {
      return getConnection();
    }
  }
);
}
 

Example 29

From project Cafe, under directory /webapp/src/org/openqa/selenium/net/.

Source file: PortProber.java

  29 
vote

public static Callable<Integer> freeLocalPort(final int port){
  return new Callable<Integer>(){
    public Integer call() throws Exception {
      if (checkPortIsFree(port) != -1) {
        return port;
      }
      return null;
    }
  }
;
}
 

Example 30

From project CamelInAction-source, under directory /chapter10/client/src/test/java/camelinaction/.

Source file: JavaFutureTest.java

  29 
vote

@Test public void testFutureWithDone() throws Exception {
  Callable<String> task=new Callable<String>(){
    public String call() throws Exception {
      LOG.info("Starting to process task");
      Thread.sleep(5000);
      LOG.info("Task is now done");
      return "Camel rocks";
    }
  }
;
  ExecutorService executor=Executors.newCachedThreadPool();
  LOG.info("Submitting task to ExecutorService");
  Future<String> future=executor.submit(task);
  LOG.info("Task submitted and we got a Future handle");
  boolean done=false;
  while (!done) {
    done=future.isDone();
    LOG.info("Is the task done? " + done);
    if (!done) {
      Thread.sleep(2000);
    }
  }
  String answer=future.get();
  LOG.info("The answer is: " + answer);
}
 

Example 31

From project capedwarf-blue, under directory /channel/src/main/java/org/jboss/capedwarf/channel/util/.

Source file: ClusterUtils.java

  29 
vote

public static void submitToAllNodes(Callable<Void> task){
  if (isStandalone()) {
    executeLocally(task);
  }
 else {
    executeOnAllNodes(task);
  }
}
 

Example 32

From project Carolina-Digital-Repository, under directory /fcrepo-clients/src/main/java/edu/unc/lib/dl/fedora/.

Source file: FedoraDataService.java

  29 
vote

/** 
 * Retrieves a view-inputs document containing the FOXML datastream for the object identified by simplepid
 * @param simplepid
 * @return
 * @throws FedoraException
 */
public Document getFoxmlViewXML(String simplepid) throws FedoraException {
  final PID pid=new PID(simplepid);
  Document result=new Document();
  final Element inputs=new Element("view-inputs");
  result.setRootElement(inputs);
  List<Callable<Content>> callables=new ArrayList<Callable<Content>>();
  callables.add(new GetFoxml(pid));
  this.retrieveAsynchronousResults(inputs,callables,pid,true);
  return result;
}
 

Example 33

From project cascading, under directory /src/core/cascading/cascade/.

Source file: Cascade.java

  29 
vote

private void initializeNewJobsMap(){
  jobsMap=new LinkedHashMap<String,Callable<Throwable>>();
  TopologicalOrderIterator<Flow,Integer> topoIterator=flowGraph.getTopologicalIterator();
  while (topoIterator.hasNext()) {
    Flow flow=topoIterator.next();
    cascadeStats.addFlowStats(flow.getFlowStats());
    CascadeJob job=new CascadeJob(flow);
    jobsMap.put(flow.getName(),job);
    List<CascadeJob> predecessors=new ArrayList<CascadeJob>();
    for (    Flow predecessor : Graphs.predecessorListOf(flowGraph,flow))     predecessors.add((CascadeJob)jobsMap.get(predecessor.getName()));
    job.init(predecessors);
  }
}
 

Example 34

From project caustic, under directory /test/test/net/caustic/database/.

Source file: DatabaseTest.java

  29 
vote

@Test public void testConcurrency() throws Exception {
  Map<String,String> comparison=new HashMap<String,String>();
  for (int i=0; i < 100; i++) {
    final String name=randomString();
    final String value=randomString();
    comparison.put(name,value);
    exc.submit(new Callable<Void>(){
      public Void call() throws Exception {
        db.put(scope,name,value);
        return null;
      }
    }
);
  }
  exc.shutdown();
  if (exc.awaitTermination(10,TimeUnit.SECONDS) == false) {
    exc.shutdownNow();
    throw new InterruptedException("Didn't finish in ten seconds.");
  }
  for (  Map.Entry<String,String> entry : comparison.entrySet()) {
    assertEquals(entry.getValue(),db.get(scope,entry.getKey()));
  }
}
 

Example 35

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/byon/.

Source file: ByonProvisioningDriver.java

  29 
vote

@Override protected void initDeployer(final Cloud cloud){
  try {
    deployer=(ByonDeployer)context.getOrCreate("UNIQUE_BYON_DEPLOYER_ID",new Callable<Object>(){
      @SuppressWarnings("unchecked") @Override public Object call() throws Exception {
        logger.info("Creating BYON context deployer for cloud: " + cloud.getName());
        final ByonDeployer deployer=new ByonDeployer();
        List<Map<String,String>> nodesList=null;
        final Map<String,CloudTemplate> templatesMap=cloud.getTemplates();
        for (        final String templateName : templatesMap.keySet()) {
          final Map<String,Object> customSettings=cloud.getTemplates().get(templateName).getCustom();
          if (customSettings != null) {
            nodesList=(List<Map<String,String>>)customSettings.get(CLOUD_NODES_LIST);
          }
          if (nodesList == null) {
            publishEvent("prov_invalid_configuration");
            throw new CloudProvisioningException("Failed to create BYON cloud deployer, invalid configuration");
          }
          deployer.addNodesList(templateName,nodesList);
        }
        return deployer;
      }
    }
);
  }
 catch (  final Exception e) {
    publishEvent("connection_to_cloud_api_failed",cloud.getProvider().getProvider());
    throw new IllegalStateException("Failed to create cloud deployer",e);
  }
  setCustomSettings(cloud);
}
 

Example 36

From project clustermeister, under directory /api/src/main/java/com/github/nethad/clustermeister/api/impl/.

Source file: ClustermeisterImpl.java

  29 
vote

@Override public <T>ListenableFuture<List<T>> executeJobAsync(final Job<T> job) throws Exception {
  return threadsExecutorService.submit(new Callable<List<T>>(){
    @Override public List<T> call() throws Exception {
      return executeJob(job);
    }
  }
);
}
 

Example 37

From project coffeescript-netbeans, under directory /src/coffeescript/nb/.

Source file: CoffeeScriptParser.java

  29 
vote

public void parse(final Snapshot snapshot,Task task,SourceModificationEvent event) throws ParseException {
  future=PARSER_TASK.submit(new Callable<ParsingResult>(){
    public ParsingResult call() throws Exception {
      CharSequence text=snapshot.getText();
      CoffeeScriptCompiler.CompilerResult compilerResult=CoffeeScriptSettings.getCompiler().compile(text.toString(),CoffeeScriptSettings.get().isBare());
      return new ParsingResult(snapshot,compilerResult);
    }
  }
);
}
 

Example 38

From project com.cedarsoft.serialization, under directory /serialization/src/test/java/com/cedarsoft/serialization/.

Source file: SplittingPerformanceRunner.java

  29 
vote

private static void run(@Nonnull String description,@Nonnull Callable<String> callable) throws Exception {
  for (int i=0; i < 1000; i++) {
    assertEquals("1.0.0",callable.call());
  }
  StopWatch stopWatch=new StopWatch();
  stopWatch.start();
  for (int i=0; i < 100000; i++) {
    assertEquals("1.0.0",callable.call());
  }
  stopWatch.stop();
  System.out.println(description + " took " + stopWatch.getTime());
}
 

Example 39

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

Source file: JavaScriptThreadModel.java

  29 
vote

public Object evaluate(final URL url) throws IOException {
  FutureTask<Object> future=new FutureTask<Object>(new Callable<Object>(){
    public Object call() throws IOException {
      return context.evaluateReader(rootScope,new InputStreamReader(url.openStream()),url.toExternalForm(),1,null);
    }
  }
);
  submit(future);
  try {
    return future.get();
  }
 catch (  InterruptedException x) {
    Thread.currentThread().interrupt();
    return null;
  }
catch (  ExecutionException x) {
    Throwable xx=x.getCause();
    if (xx instanceof IOException)     throw (IOException)xx;
    if (xx instanceof Error)     throw (Error)xx;
    throw (RuntimeException)xx;
  }
}
 

Example 40

From project components, under directory /soap/src/test/java/org/switchyard/component/soap/.

Source file: SOAPGatewayTest.java

  29 
vote

@Test public void invokeMultiThreaded() throws Exception {
  String output=null;
  String response=null;
  Collection<Callable<String>> callables=new ArrayList<Callable<String>>();
  for (int i=0; i < _noOfThreads; i++) {
    callables.add(new WebServiceInvoker(i));
  }
  ExecutorService executorService=Executors.newFixedThreadPool(DEFAULT_THREAD_COUNT);
  Collection<Future<String>> futures=executorService.invokeAll(callables);
  Assert.assertEquals(futures.size(),_noOfThreads);
  int i=0;
  for (  Future<String> future : futures) {
    response=future.get();
    output="<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<SOAP-ENV:Body>" + "   <test:sayHelloResponse xmlns:test=\"urn:switchyard-component-soap:test-ws:1.0\">"+ "      <return>Hello Thread " + i + "! The soapAction received is </return>"+ "   </test:sayHelloResponse>"+ "</SOAP-ENV:Body></SOAP-ENV:Envelope>";
    XMLAssert.assertXMLEqual(output,response);
    i++;
  }
}
 

Example 41

From project components-ness-hbase, under directory /src/main/java/com/nesscomputing/hbase/.

Source file: HBaseWriter.java

  29 
vote

@Override public Put apply(@Nullable final Callable<Put> callable){
  try {
    return callable == null ? null : callable.call();
  }
 catch (  Exception e) {
    throw Throwables.propagate(e);
  }
}