Java Code Examples for java.util.concurrent.TimeoutException

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 amplafi-sworddance, under directory /src/main/java/com/sworddance/taskcontrol/.

Source file: FutureResultImpl.java

  19 
vote

@Override public T get(long timeout,TimeUnit unit) throws TimeoutException, InterruptedException, ExecutionException {
  try {
    return super.get(timeout,unit);
  }
 catch (  TimeoutException exception) {
    throw new TimeoutException("waited " + timeout + unit);
  }
}
 

Example 2

From project c24-spring, under directory /c24-spring-batch/src/main/java/biz/c24/io/spring/batch/reader/.

Source file: C24BatchItemReader.java

  19 
vote

private void queueObject(ComplexDataObject obj) throws TimeoutException, InterruptedException {
  if (!queue.offer(obj,10,TimeUnit.SECONDS)) {
    TimeoutException ex=new TimeoutException("Timed out waiting for parsed elements to be processed. Aborting.");
    throw ex;
  }
}
 

Example 3

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/.

Source file: CallFuture.java

  18 
vote

@Override public T get(long timeout,TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
  if (latch.await(timeout,unit)) {
    if (error != null) {
      throw new ExecutionException(error);
    }
    return result;
  }
 else {
    throw new TimeoutException();
  }
}
 

Example 4

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/run/.

Source file: BlackBoard.java

  18 
vote

public synchronized OBJECT getObject(KEY key) throws TimeoutException, InterruptedException {
  int timeout=0;
  while ((!map.containsKey(key) && (timeout < BPELUnitRunner.getTimeout()))) {
    timeout+=BPELUnitConstants.TIMEOUT_SLEEP_TIME;
    wait(BPELUnitConstants.TIMEOUT_SLEEP_TIME);
  }
  if (timeout >= BPELUnitRunner.getTimeout()) {
    throw new TimeoutException("Waiting for object for key " + key + " took too long.");
  }
  OBJECT object=map.get(key);
  map.remove(key);
  notifyAll();
  return object;
}
 

Example 5

From project android-marvin, under directory /marvin/src/main/java/de/akquinet/android/marvin/actions/.

Source file: PerformAction.java

  17 
vote

private IBinder bindService(Intent serviceIntent,Class<?> serviceClass,int flags,int timeout,TimeUnit timeUnit) throws TimeoutException {
  TemporaryServiceConnection serviceConnection=new TemporaryServiceConnection(timeout,timeUnit);
  instrumentation.getTargetContext().bindService(serviceIntent,serviceConnection,flags);
  IBinder serviceBinder=serviceConnection.getBinderSync();
  if (serviceBinder == null) {
    throw new TimeoutException("Timeout hit (" + timeout + " "+ timeUnit.toString().toLowerCase()+ ") while trying to connect to service"+ serviceClass != null ? " " + serviceClass.getName() : "" + ".");
  }
  serviceConnections.put(serviceBinder,serviceConnection);
  return serviceBinder;
}
 

Example 6

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

Source file: AbstractFuture.java

  17 
vote

/** 
 * Blocks until the task is complete or the timeout expires.  Throws a {@link TimeoutException} if the timer expires, otherwise behaves like{@link #get()}.
 */
V get(long nanos) throws TimeoutException, CancellationException, ExecutionException, InterruptedException {
  if (!tryAcquireSharedNanos(-1,nanos)) {
    throw new TimeoutException("Timeout waiting for task.");
  }
  return getValue();
}
 

Example 7

From project cloudify, under directory /CLI/src/main/java/org/cloudifysource/shell/.

Source file: ConditionLatch.java

  17 
vote

/** 
 * Waits for the given predicate to complete. The predicate is monitored according to the specified polling interval. If the timeout is reached before the predicate is done, a timeout exception is thrown.
 * @param predicate The predicate to monitor
 * @throws InterruptedException Reporting the thread was interrupted while waiting
 * @throws TimeoutException Reporting the timeout was reached
 * @throws CLIException Reporting a failure to monitor the predicate's status
 */
public void waitFor(final Predicate predicate) throws InterruptedException, TimeoutException, CLIException {
  final long end=System.currentTimeMillis() + timeoutMilliseconds;
  boolean isDone=predicate.isDone();
  while (!isDone && System.currentTimeMillis() < end) {
    if (verbose) {
      logger.log(Level.FINE,"\nnext check in " + TimeUnit.MILLISECONDS.toSeconds(pollingIntervalMilliseconds) + " seconds");
    }
    Thread.sleep(pollingIntervalMilliseconds);
    isDone=predicate.isDone();
  }
  if (!isDone && System.currentTimeMillis() >= end) {
    throw new TimeoutException(timeoutErrorMessage);
  }
}
 

Example 8

From project datasalt-utils, under directory /src/contrib/java/org/apache/solr/common/cloud/.

Source file: ConnectionManager.java

  17 
vote

public synchronized void waitForConnected(long waitForConnection) throws InterruptedException, TimeoutException, IOException {
  long expire=System.currentTimeMillis() + waitForConnection;
  long left=waitForConnection;
  while (!connected && left > 0) {
    wait(left);
    left=expire - System.currentTimeMillis();
  }
  if (!connected) {
    throw new TimeoutException("Could not connect to ZooKeeper " + zkServerAddress + " within "+ waitForConnection+ " ms");
  }
}
 

Example 9

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

Source file: DefaultDbFuture.java

  16 
vote

public T get(long timeout,TimeUnit unit) throws InterruptedException, DbException, TimeoutException {
  long timeoutMillis=unit.toMillis(timeout);
  if (done) {
    return getResult();
  }
synchronized (lock) {
    if (done) {
      return getResult();
    }
    waiters++;
    try {
      lock.wait(timeoutMillis);
      if (!done) {
        throw new TimeoutException();
      }
    }
  finally {
      waiters--;
    }
  }
  return getResult();
}
 

Example 10

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

Source file: ImplicitWorkStealingRuntime.java

  16 
vote

@Override public Object get(long timeout,TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
  final long start=System.nanoTime();
  while (System.nanoTime() < start + unit.toNanos(timeout)) {
    if (!task.isCompleted()) {
      Thread.sleep(1);
    }
  }
  if (task.isCompleted()) {
    Object result=task.getResult();
    if (result instanceof Exception) {
      throw new ExecutionException((Exception)result);
    }
 else {
      return result;
    }
  }
 else {
    throw new TimeoutException();
  }
}
 

Example 11

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

Source file: HttpCommandConnectionPool.java

  16 
vote

protected C getConnection() throws InterruptedException, TimeoutException {
  exceptionIfNotActive();
  if (!hitBottom) {
    hitBottom=available.size() == 0 && allConnections.availablePermits() == 0;
    if (hitBottom)     logger.warn("saturated connection pool");
  }
  logger.trace("Blocking up to %ds for a connection to %s",5,getEndPoint());
  C conn=available.poll(5,TimeUnit.SECONDS);
  if (conn == null)   throw new TimeoutException(String.format("Timeout after %ds for a connection to %s",5,getEndPoint()));
  if (connectionValid(conn)) {
    return conn;
  }
 else {
    logger.debug("Connection %s unusable for endpoint %s",conn.hashCode(),getEndPoint());
    shutdownConnection(conn);
    allConnections.release();
    return getConnection();
  }
}
 

Example 12

From project android-rss, under directory /src/main/java/org/mcsoxford/rss/.

Source file: RSSLoader.java

  16 
vote

@Override public synchronized RSSFeed get(long timeout,TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
  if (feed == null && cause == null) {
    try {
      waiting=true;
      final long timeoutMillis=unit.toMillis(timeout);
      final long startMillis=System.currentTimeMillis();
      while (waiting) {
        wait(timeoutMillis);
        if (System.currentTimeMillis() - startMillis > timeoutMillis) {
          throw new TimeoutException("RSS feed loading timed out");
        }
      }
    }
  finally {
      waiting=false;
    }
  }
  if (cause != null) {
    throw new ExecutionException(cause);
  }
  return feed;
}
 

Example 13

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

Source file: AwaitilityTest.java

  16 
vote

@Test(timeout=2000,expected=TimeoutException.class) public void whenDontCatchUncaughtExceptionsIsSpecifiedThenExceptionsFromOtherThreadsAreNotCaught() throws Exception {
  new AssertExceptionThrownInAnotherThreadButNeverCaughtByAnyThreadTest(){
    @Override public void testLogic() throws Exception {
      new ExceptionThrowingAsynch().perform();
      dontCatchUncaughtExceptions().and().await().atMost(ONE_SECOND).until(value(),equalTo(1));
    }
  }
;
}
 

Example 14

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

Source file: BlueprintEventDispatcher.java

  16 
vote

private void callListener(final BlueprintListener listener,final BlueprintEvent event) throws RejectedExecutionException {
  try {
    executor.invokeAny(Collections.<Callable<Void>>singleton(new Callable<Void>(){
      public Void call() throws Exception {
        listener.blueprintEvent(event);
        return null;
      }
    }
),60L,TimeUnit.SECONDS);
  }
 catch (  InterruptedException ie) {
    LOGGER.warn("Thread interrupted",ie);
    Thread.currentThread().interrupt();
  }
catch (  TimeoutException te) {
    LOGGER.warn("Listener timed out, will be ignored",te);
    listeners.remove(listener);
  }
catch (  ExecutionException ee) {
    LOGGER.warn("Listener caused an exception, will be ignored",ee);
    listeners.remove(listener);
  }
}
 

Example 15

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

Source file: NodeManagementConnector.java

  16 
vote

public static JMXConnectionWrapper connectToNodeManagement(JMXConnectionWrapper wrapper) throws TimeoutException {
  wrapper.connectAndWait(3000);
  if (!wrapper.isConnected()) {
    wrapper.connectAndWait(5000);
    if (!wrapper.isConnected()) {
      wrapper.connectAndWait(180000);
    }
  }
  if (wrapper.isConnected()) {
    return wrapper;
  }
 else {
    throw new TimeoutException("Timed out while for node JMX management to become available.");
  }
}
 

Example 16

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

Source file: AbstractTestExportService.java

  16 
vote

private void waitPort(int port) throws Exception {
  for (int i=0; i < 20; i++) {
    Socket s=null;
    try {
      s=new Socket((String)null,port);
      return;
    }
 catch (    IOException e) {
    }
 finally {
      if (s != null) {
        try {
          s.close();
        }
 catch (        IOException e) {
        }
      }
    }
    System.out.println("Waiting for server to appear on port: " + port);
    Thread.sleep(1000);
  }
  throw new TimeoutException();
}
 

Example 17

From project DirectMemory, under directory /server/directmemory-server-client/src/main/java/org/apache/directmemory/server/client/providers/asynchttpclient/.

Source file: AsyncHttpClientDirectMemoryHttpClient.java

  16 
vote

@Override public DirectMemoryResponse put(DirectMemoryRequest request) throws DirectMemoryException {
  try {
    return internalPut(request).get(configuration.getReadTimeOut(),TimeUnit.MILLISECONDS);
  }
 catch (  InterruptedException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
catch (  TimeoutException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
catch (  ExecutionException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
}
 

Example 18

From project anadix, under directory /integration/anadix-selenium/src/main/java/org/anadix/utils/.

Source file: MultithreadedAnalyzer.java

  15 
vote

public Report getResult(int id,boolean block) throws ResultException {
  Future<Report> future=results.get(id);
  try {
    if (future != null) {
      if (block) {
        return future.get();
      }
 else {
        try {
          return future.get(1,TimeUnit.MILLISECONDS);
        }
 catch (        TimeoutException ex) {
        }
      }
    }
  }
 catch (  InterruptedException ex) {
    throw new ResultException("Interrupted",ex);
  }
catch (  ExecutionException ex) {
    throw new ResultException("Error during execution",ex.getCause());
  }
  return null;
}
 

Example 19

From project any23, under directory /plugins/basic-crawler/src/test/java/org/apache/any23/cli/.

Source file: CrawlerTest.java

  15 
vote

@Test public void testCLI() throws IOException, RDFHandlerException, RDFParseException {
  assumeOnlineAllowed();
  final File outFile=File.createTempFile("crawler-test",".nq",tempDirectory);
  outFile.delete();
  logger.info("Outfile: " + outFile.getAbsolutePath());
  final Future<?> future=Executors.newSingleThreadExecutor().submit(new Runnable(){
    @Override public void run(){
      try {
        ToolRunner.main(String.format("crawler -f nquads --maxpages 50 --maxdepth 1 --politenessdelay 500 -o %s " + "http://eventiesagre.it/",outFile.getAbsolutePath()).split(" "));
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
    }
  }
);
  try {
    future.get(10,TimeUnit.SECONDS);
  }
 catch (  Exception e) {
    if (!(e instanceof TimeoutException)) {
      e.printStackTrace();
    }
  }
  assertTrue("The output file has not been created.",outFile.exists());
  final String[] lines=FileUtils.readFileLines(outFile);
  final StringBuilder allLinesExceptLast=new StringBuilder();
  for (int i=0; i < lines.length - 1; i++) {
    allLinesExceptLast.append(lines[i]);
  }
  final Statement[] statements=RDFUtils.parseRDF(RDFFormat.NQUADS,allLinesExceptLast.toString());
  assertTrue(statements.length > 0);
}
 

Example 20

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

Source file: EmulatorShutdown.java

  15 
vote

/** 
 * This method contains the code required to stop an emulator.
 * @return {@code true} if stopped without errors, {@code false} otherwise
 * @param device The device to stop
 */
private Boolean stopEmulator(final Process p,final ProcessExecutor executor,final AndroidDevice device,final CountDownWatch countdown) throws AndroidExecutionException {
  int devicePort=extractPortFromDevice(device);
  if (devicePort == -1) {
    log.log(Level.SEVERE,"Unable to retrieve port to stop emulator {0}",device.getSerialNumber());
    return false;
  }
 else {
    log.log(Level.FINER,"Stopping emulator {0} via port {1}",new Object[]{device.getSerialNumber(),devicePort});
    try {
      Boolean stopped=executor.submit(sendEmulatorCommand(devicePort,"avd stop")).get(countdown.timeLeft(),countdown.getTimeUnit());
      log.log(Level.FINE,"Command avd stop executed, {0} seconds remaining to dispose the device",countdown.timeLeft());
      if (stopped == false) {
        stopped=executor.submit(sendEmulatorCommand(devicePort,"kill")).get(countdown.timeLeft(),countdown.getTimeUnit());
      }
      log.log(Level.FINE,"Command kill executed, {0} seconds remaining to dispose the device",countdown.timeLeft());
      int retval=executor.submit(new Callable<Integer>(){
        @Override public Integer call() throws Exception {
          return p.waitFor();
        }
      }
).get(5,TimeUnit.SECONDS);
      log.log(Level.FINE,"Emulator process returned {0}, {1} seconds remaining to dispose the device",new Object[]{retval,countdown.timeLeft()});
      return stopped == true && retval == 0;
    }
 catch (    TimeoutException e) {
      p.destroy();
      log.log(Level.WARNING,"Emulator process was forcibly destroyed, {0} seconds remaining to dispose the device",countdown.timeLeft());
      return false;
    }
catch (    InterruptedException e) {
      p.destroy();
      throw new AndroidExecutionException(e,"Unable to stop emulator {0}",device.getAvdName());
    }
catch (    ExecutionException e) {
      p.destroy();
      throw new AndroidExecutionException(e,"Unable to stop emulator {0}",device.getAvdName());
    }
  }
}
 

Example 21

From project astyanax, under directory /src/test/java/com/netflix/astyanax/thrift/.

Source file: ThrifeKeyspaceImplTest.java

  15 
vote

@Test public void testGetSingleColumnNotExistsAsync(){
  Future<OperationResult<Column<String>>> future=null;
  try {
    future=keyspace.prepareQuery(CF_STANDARD1).getKey("A").getColumn("DoesNotExist").executeAsync();
    future.get(1000,TimeUnit.MILLISECONDS);
  }
 catch (  ConnectionException e) {
    LOG.info("ConnectionException: " + e.getMessage());
    Assert.fail();
  }
catch (  InterruptedException e) {
    LOG.info(e.getMessage());
    Assert.fail();
  }
catch (  ExecutionException e) {
    if (e.getCause() instanceof NotFoundException)     LOG.info(e.getCause().getMessage());
 else {
      Assert.fail(e.getMessage());
    }
  }
catch (  TimeoutException e) {
    future.cancel(true);
    LOG.info(e.getMessage());
    Assert.fail();
  }
}
 

Example 22

From project autopsy, under directory /KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/.

Source file: Ingester.java

  15 
vote

/** 
 * Delegate method actually performing the indexing work for objects implementing ContentStream
 * @param cs ContentStream to ingest
 * @param fields content specific fields
 * @param size size of the content - used to determine the Solr timeout, notused to populate meta-data
 * @throws IngesterException if there was an error processing a specificcontent, but the Solr server is probably fine.
 */
private void ingest(ContentStream cs,Map<String,String> fields,final long size) throws IngesterException {
  final ContentStreamUpdateRequest up=new ContentStreamUpdateRequest("/update/extract");
  up.addContentStream(cs);
  setFields(up,fields);
  up.setAction(AbstractUpdateRequest.ACTION.COMMIT,true,true);
  final String contentType=cs.getContentType();
  if (contentType != null && !contentType.trim().equals("")) {
    up.setParam("stream.contentType",contentType);
  }
  up.setParam("commit","false");
  final Future<?> f=upRequestExecutor.submit(new UpRequestTask(up));
  try {
    f.get(getTimeout(size),TimeUnit.SECONDS);
  }
 catch (  TimeoutException te) {
    logger.log(Level.WARNING,"Solr timeout encountered, trying to restart Solr");
    hardSolrRestart();
    throw new IngesterException("Solr index request time out for id: " + fields.get("id") + ", name: "+ fields.get("file_name"));
  }
catch (  Exception e) {
    throw new IngesterException("Problem posting content to Solr, id: " + fields.get("id") + ", name: "+ fields.get("file_name"),e);
  }
  uncommitedIngests=true;
}
 

Example 23

From project camel-zookeeper, under directory /src/main/java/org/apache/camel/component/zookeeper/operations/.

Source file: FutureEventDrivenOperation.java

  15 
vote

public OperationResult<ResultType> get(long timeout,TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
  installWatch();
  waitingThreads.add(Thread.currentThread());
  waitForAnyWatchedType.await(timeout,unit);
  return result;
}
 

Example 24

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/monitor/.

Source file: AbstractPoolMonitor.java

  15 
vote

/** 
 * {@inheritDoc} 
 */
public PoolStatus observe(){
  final Future<StatusCode> result=this.executor.submit(new Validator());
  StatusCode code;
  String description=null;
  try {
    code=result.get(this.maxWait,TimeUnit.MILLISECONDS);
  }
 catch (  final InterruptedException e) {
    code=StatusCode.UNKNOWN;
    description="Validator thread interrupted during pool validation.";
  }
catch (  final TimeoutException e) {
    code=StatusCode.WARN;
    description=String.format("Pool validation timed out.  Max wait is %s ms.",this.maxWait);
  }
catch (  final Exception e) {
    code=StatusCode.ERROR;
    description=e.getMessage();
  }
  return new PoolStatus(code,description,getActiveCount(),getIdleCount());
}
 

Example 25

From project cometd, under directory /cometd-java/cometd-java-client/src/test/java/org/cometd/client/.

Source file: MaxNetworkDelayTest.java

  15 
vote

@Test public void testMaxNetworkDelayOnHandshake() throws Exception {
  final long maxNetworkDelay=2000;
  final long sleep=maxNetworkDelay + maxNetworkDelay / 2;
  bayeux.addExtension(new BayeuxServer.Extension.Adapter(){
    @Override public boolean sendMeta(    ServerSession to,    ServerMessage.Mutable message){
      if (Channel.META_HANDSHAKE.equals(message.getChannel())) {
        try {
          Thread.sleep(sleep);
        }
 catch (        InterruptedException x) {
          Thread.currentThread().interrupt();
        }
      }
      return true;
    }
  }
);
  final CountDownLatch latch=new CountDownLatch(2);
  LongPollingTransport transport=LongPollingTransport.create(null,httpClient);
  transport.setOption(ClientTransport.MAX_NETWORK_DELAY_OPTION,maxNetworkDelay);
  BayeuxClient client=new BayeuxClient(cometdURL,transport){
    @Override public void onFailure(    Throwable x,    Message[] messages){
      if (x instanceof TimeoutException)       latch.countDown();
    }
  }
;
  client.setDebugEnabled(debugTests());
  client.getChannel(Channel.META_HANDSHAKE).addListener(new ClientSessionChannel.MessageListener(){
    public void onMessage(    ClientSessionChannel channel,    Message message){
      if (!message.isSuccessful())       latch.countDown();
    }
  }
);
  client.handshake();
  assertTrue(latch.await(sleep,TimeUnit.MILLISECONDS));
  disconnectBayeuxClient(client);
}
 

Example 26

From project cron, under directory /tck/src/test/java/org/jboss/seam/cron/test/asynchronous/tck/.

Source file: SeamCronAsynchronousTCKTest.java

  15 
vote

@Test public void testAsynchReturningFuture() throws InterruptedException, InterruptedException, ExecutionException, TimeoutException {
  log.info("Testing asynchronous methods return a future as expected");
  assertNotNull(asynchBean);
  asynchBean.reset();
  assertNull(asynchBean.getStatusEvent());
  assertNull(asynchBean.getHaystackCount());
  String statusToSet="blue";
  Future<Status> result=asynchBean.returnStatusInFuture(statusToSet);
  assertNotNull(result);
  Status resultStatus=result.get(4,TimeUnit.SECONDS);
  assertNotNull(resultStatus);
  assertNotNull(resultStatus.getDescription());
  assertEquals(statusToSet,resultStatus.getDescription());
  assertNull(asynchBean.getHaystackCount());
}