Java Code Examples for java.util.concurrent.TimeUnit

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 airlift, under directory /units/src/main/java/io/airlift/units/.

Source file: Duration.java

  19 
vote

public static Duration valueOf(String duration) throws IllegalArgumentException {
  Preconditions.checkNotNull(duration,"duration is null");
  Preconditions.checkArgument(!duration.isEmpty(),"duration is empty");
  Matcher matcher=DURATION_PATTERN.matcher(duration);
  if (!matcher.matches()) {
    throw new IllegalArgumentException("duration is not a valid duration string: " + duration);
  }
  String magnitudeString=matcher.group(1);
  double magnitude=Double.parseDouble(magnitudeString);
  String timeUnitString=matcher.group(2);
  TimeUnit timeUnit;
  if (timeUnitString.equals("ms")) {
    timeUnit=TimeUnit.MILLISECONDS;
  }
 else   if (timeUnitString.equals("s")) {
    timeUnit=TimeUnit.SECONDS;
  }
 else   if (timeUnitString.equals("m")) {
    timeUnit=TimeUnit.MINUTES;
  }
 else   if (timeUnitString.equals("h")) {
    timeUnit=TimeUnit.HOURS;
  }
 else   if (timeUnitString.equals("d")) {
    timeUnit=TimeUnit.DAYS;
  }
 else {
    throw new IllegalArgumentException("Unknown time unit: " + timeUnitString);
  }
  return new Duration(magnitude,timeUnit);
}
 

Example 2

From project accent, under directory /src/test/java/net/lshift/accent/.

Source file: ConnectionBehaviourTest.java

  15 
vote

@Test public void shouldKeepAttemptingToReconnect() throws Exception {
  ConnectionFactory unconnectableFactory=createMock(ConnectionFactory.class);
  expect(unconnectableFactory.newConnection()).andStubThrow(new ConnectException("Boom"));
  replay(unconnectableFactory);
  final CountDownLatch attemptLatch=new CountDownLatch(4);
  ConnectionFailureListener eventingListener=new ConnectionFailureListener(){
    @Override public void connectionFailure(    Exception e){
      if (e instanceof ConnectException) {
        attemptLatch.countDown();
      }
 else {
        System.out.println("WARNING: Received unexpected exception - " + e);
      }
    }
  }
;
  AccentConnection conn=new AccentConnection(unconnectableFactory,eventingListener);
  assertTrue(attemptLatch.await(5000,TimeUnit.MILLISECONDS));
}
 

Example 3

From project ACLS-protocol-library, under directory /aclslib/src/test/java/au/edu/uq/cmm/acslib/service/.

Source file: MonitoredThreadServiceBaseTest.java

  15 
vote

@Test public void testStartupShutdown() throws InterruptedException {
  BlockingDeque<String> status=new LinkedBlockingDeque<String>();
  AtomicBoolean killSwitch=new AtomicBoolean();
  Service service=new MTSBTestService(status,killSwitch,1,1,500);
  Assert.assertNull(status.pollFirst());
  Assert.assertEquals(State.INITIAL,service.getState());
  service.startup();
  Assert.assertEquals(State.STARTED,service.getState());
  Assert.assertEquals("running",status.pollFirst(2,TimeUnit.SECONDS));
  service.shutdown();
  Assert.assertEquals(State.STOPPED,service.getState());
  Assert.assertEquals("finished",status.pollFirst(2,TimeUnit.SECONDS));
}
 

Example 4

From project activemq-apollo, under directory /apollo-distro/src/main/release/examples/openwire/jms-example-message-browser/src/main/java/example/browser/.

Source file: Browser.java

  15 
vote

public static void main(String[] args){
  ActiveMQConnectionFactory connectionFactory=new ActiveMQConnectionFactory("admin","password",BROKER_URL);
  Connection connection=null;
  try {
    connection=connectionFactory.createConnection();
    connection.start();
    Session session=connection.createSession(NON_TRANSACTED,Session.AUTO_ACKNOWLEDGE);
    Queue destination=session.createQueue("test-queue");
    QueueBrowser browser=session.createBrowser(destination);
    Enumeration enumeration=browser.getEnumeration();
    while (enumeration.hasMoreElements()) {
      TextMessage message=(TextMessage)enumeration.nextElement();
      System.out.println("Browsing: " + message);
      TimeUnit.MILLISECONDS.sleep(DELAY);
    }
    session.close();
  }
 catch (  Exception e) {
    System.out.println("Caught exception!");
  }
 finally {
    if (connection != null) {
      try {
        connection.close();
      }
 catch (      JMSException e) {
        System.out.println("Could not close an open connection...");
      }
    }
  }
}
 

Example 5

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

Source file: DbFutureConcurrentProxy.java

  15 
vote

public T get(long timeout,TimeUnit unit) throws DbException, InterruptedException, TimeoutException {
  try {
    if (isDone() && set) {
      return value;
    }
    return future.get(timeout,unit);
  }
 catch (  ExecutionException e) {
    throw new DbException(e);
  }
}
 

Example 6

From project AdminStuff, under directory /src/main/java/de/minestar/AdminStuff/commands/.

Source file: cmdButcher.java

  15 
vote

@Override public void execute(String[] args,Player player){
  if (args.length == 0) {
    Long lastTime=recentUser.get(player);
    if (lastTime == null || (System.currentTimeMillis() - lastTime >= TimeUnit.MINUTES.toMillis(5))) {
      PlayerUtils.sendMessage(player,ChatColor.MAGIC,"-------------------------------------------");
      PlayerUtils.sendError(player,pluginName,"Wenn du wirklich alle Tiere ?er den Jordan schicken willst,");
      PlayerUtils.sendError(player,pluginName,"(Das sind ca. " + countMobs(player.getWorld()) + " Tiere! Denk mal an deren Kinder!)");
      PlayerUtils.sendError(player,pluginName,"Dann gebe bitte den Befehl ein 2. Mal ein und lebe mit den Folgen!");
      PlayerUtils.sendMessage(player,ChatColor.MAGIC,"-------------------------------------------");
      recentUser.put(player,System.currentTimeMillis());
    }
 else {
      killAll(player);
      recentUser.remove(player);
    }
  }
 else   if (args.length == 1) {
    int radius=0;
    try {
      radius=Integer.parseInt(args[0]);
    }
 catch (    Exception e) {
      PlayerUtils.sendError(player,pluginName,args[0] + " ist keine Zahl!");
      return;
    }
    killRadius(player,radius);
  }
 else   PlayerUtils.sendError(player,pluginName,getHelpMessage());
}
 

Example 7

From project AdServing, under directory /modules/utilities/common/src/main/java/biz/source_code/miniConnectionPoolManager/.

Source file: MiniConnectionPoolManager.java

  15 
vote

private Connection getConnection2(long timeoutMs) throws SQLException {
synchronized (this) {
    if (isDisposed) {
      throw new IllegalStateException("Connection pool has been disposed.");
    }
  }
  try {
    if (!semaphore.tryAcquire(timeoutMs,TimeUnit.MILLISECONDS)) {
      throw new TimeoutException();
    }
  }
 catch (  InterruptedException e) {
    throw new RuntimeException("Interrupted while waiting for a database connection.",e);
  }
  boolean ok=false;
  try {
    Connection conn=getConnection3();
    ok=true;
    return conn;
  }
  finally {
    if (!ok) {
      semaphore.release();
    }
  }
}
 

Example 8

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

Source file: ImplicitWorkStealingRuntime.java

  15 
vote

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

Example 9

From project aether-core, under directory /aether-connector-file/src/main/java/org/eclipse/aether/connector/file/.

Source file: ParallelRepositoryConnector.java

  15 
vote

protected void initExecutor(Map<String,Object> config){
  if (executor == null) {
    int threads=ConfigUtils.getInteger(config,MAX_POOL_SIZE,CFG_PREFIX + ".threads");
    if (threads <= 1) {
      executor=new Executor(){
        public void execute(        Runnable command){
          command.run();
        }
      }
;
    }
 else {
      ThreadFactory threadFactory=new RepositoryConnectorThreadFactory(getClass().getSimpleName());
      executor=new ThreadPoolExecutor(threads,threads,3,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(),threadFactory);
    }
  }
}
 

Example 10

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageSchema/.

Source file: DatabaseDefn.java

  15 
vote

/** 
 * There should be one DatabaseInfo object per agileBase application instance. This constructor generates it. It bootstraps the application. All schema objects are loaded into memory from the pervasive store. The authentication manager (AuthManagerInfo), store of all users, roles and permissions is loaded too. Finally, the data manager (a DataManagementInfo object) is created and initialised
 * @throws CantDoThatException If more than one Authenticator was found in the database
 */
public DatabaseDefn(DataSource relationalDataSource,String webAppRoot) throws SQLException, ObjectNotFoundException, CantDoThatException, MissingParametersException, CodingErrorException {
  this.relationalDataSource=relationalDataSource;
  Session hibernateSession=HibernateUtil.currentSession();
  try {
    this.authManager=new AuthManager(relationalDataSource);
  }
  finally {
    HibernateUtil.closeSession();
  }
  this.dataManagement=new DataManagement(relationalDataSource,webAppRoot,this.authManager);
  DashboardPopulator dashboardPopulator=new DashboardPopulator(this);
  this.initialDashboardPopulatorThread=new Thread(dashboardPopulator);
  this.initialDashboardPopulatorThread.start();
  int hourNow=Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
  int initialDelay=24 + AppProperties.lowActivityHour - hourNow;
  this.dashboardScheduler=Executors.newSingleThreadScheduledExecutor();
  this.scheduledDashboardPopulate=dashboardScheduler.scheduleAtFixedRate(dashboardPopulator,initialDelay,24,TimeUnit.HOURS);
}
 

Example 11

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

Source file: AGConnPoolSessionTest.java

  15 
vote

private void assertSuccess(List<Future<Boolean>> errors,long timeout,TimeUnit unit) throws Exception {
  boolean fail=false;
  for (  Future<Boolean> f : errors) {
    Boolean e=f.get(timeout,unit);
    if (!e) {
      fail=true;
    }
  }
  if (fail) {
    throw new RuntimeException("See log for details.");
  }
}
 

Example 12

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/utils/.

Source file: ThreadPoolManager.java

  15 
vote

@SuppressWarnings("unchecked") public <T extends Runnable>ScheduledFuture<T> schedule(T r,long delay){
  try {
    if (delay < 0)     delay=0;
    return (ScheduledFuture<T>)scheduledThreadPool.schedule(r,delay,TimeUnit.MILLISECONDS);
  }
 catch (  RejectedExecutionException e) {
    return null;
  }
}
 

Example 13

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

Source file: Exporter.java

  15 
vote

private void scheduleRetry(final Remote object,final boolean force,final int trial){
  if (log.isDebugEnabled())   log.debug("Scheduling retry #" + trial + " of unexport for "+ object);
  Runnable job=new Runnable(){
    public void run(){
      try {
        if (log.isDebugEnabled())         log.debug("Retrying unexport for " + object);
        unexportObject(object,force,trial + 1);
      }
 catch (      NoSuchObjectException e) {
        if (log.isDebugEnabled())         log.debug(object + " is already unexported",e);
      }
    }
  }
;
  executor.schedule(job,RETRY_DELAY * trial,TimeUnit.MILLISECONDS);
}
 

Example 14

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/conn/.

Source file: AbstractClientConnAdapter.java

  15 
vote

public void setIdleDuration(long duration,TimeUnit unit){
  if (duration > 0) {
    this.duration=unit.toMillis(duration);
  }
 else {
    this.duration=-1;
  }
}
 

Example 15

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/aladdin/handler/.

Source file: CommandMessageHandler.java

  15 
vote

public void startSession() throws Exception {
  if (pools.length == 1) {
    final PoolableObject conn=(PoolableObject)pools[0].borrowObject();
    connPoolMap.put(conn,pools[0]);
    MessageHandlerRunner runnable=null;
    if (conn instanceof MessageHandlerRunnerProvider) {
      MessageHandlerRunnerProvider provider=(MessageHandlerRunnerProvider)conn;
      runnable=provider.getRunner();
    }
 else {
      runnable=newQueryRunnable(null,conn,query,parameter,packet);
    }
    runnable.init(this);
    runnable.run();
  }
 else {
    final CountDownLatch latch=new CountDownLatch(pools.length);
    for (    ObjectPool pool : pools) {
      final PoolableObject conn=(PoolableObject)pool.borrowObject();
      connPoolMap.put(conn,pool);
      QueryRunnable runnable=newQueryRunnable(latch,conn,query,parameter,packet);
      runnable.init(this);
      ProxyRuntimeContext.getInstance().getClientSideExecutor().execute(runnable);
    }
    if (timeout > 0) {
      latch.await(timeout,TimeUnit.MILLISECONDS);
    }
 else {
      latch.await();
    }
  }
  endSession();
  packet.wirteToConnection(source);
}
 

Example 16

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

Source file: DelegatingFutureCharSequence.java

  15 
vote

public CharSequence get(long timeout,TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
  if (this.loadedCharSequence == null) {
    this.loadedCharSequence=this.pendingCharSequence.get(timeout,unit);
  }
  return this.loadedCharSequence;
}
 

Example 17

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 18

From project android-client_1, under directory /src/com/buddycloud/.

Source file: TaskQueueThread.java

  15 
vote

public void run(){
  while (taskQueue != null) {
    try {
      Runnable runnable=taskQueue.poll(1800,TimeUnit.SECONDS);
      if (runnable != null) {
        runnable.run();
      }
    }
 catch (    Exception e) {
      Log.d("Service",e.toString(),e);
    }
  }
}
 

Example 19

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

Source file: AwaitAction.java

  15 
vote

@Override public final View view(final Activity activity,final int viewId,long timeout,TimeUnit timeUnit) throws TimeoutException {
  condition(new Condition("View exists and is visible"){
    @Override public boolean matches(){
      View view=activity.findViewById(viewId);
      return view != null && view.getVisibility() == View.VISIBLE;
    }
  }
,timeout,timeUnit);
  return activity.findViewById(viewId);
}
 

Example 20

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

Source file: NioHttpCommandConnectionPool.java

  15 
vote

@Override protected void createNewConnection() throws InterruptedException {
  boolean acquired=allConnections.tryAcquire(1,TimeUnit.SECONDS);
  if (acquired) {
    if (shouldDoWork()) {
      logger.trace("Opening: %s",getTarget());
      ioReactor.connect(getTarget(),null,null,sessionCallback);
    }
 else {
      allConnections.release();
    }
  }
}
 

Example 21

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

Source file: RSSLoader.java

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

From project androidannotations, under directory /HelloWorldEclipse/src/com/googlecode/androidannotations/helloworldeclipse/.

Source file: MyActivity.java

  15 
vote

@Background void someBackgroundWork(String name,long timeToDoSomeLongComputation){
  try {
    TimeUnit.SECONDS.sleep(timeToDoSomeLongComputation);
  }
 catch (  InterruptedException e) {
  }
  String message=String.format(helloFormat,name);
  updateUi(message,androidColor);
  showNotificationsDelayed();
}
 

Example 23

From project androidquery, under directory /src/com/androidquery/util/.

Source file: AQUtility.java

  15 
vote

public static void cleanCacheAsync(Context context,long triggerSize,long targetSize){
  try {
    File cacheDir=getCacheDir(context);
    Common task=new Common().method(Common.CLEAN_CACHE,cacheDir,triggerSize,targetSize);
    ScheduledExecutorService exe=getFileStoreExecutor();
    exe.schedule(task,0,TimeUnit.MILLISECONDS);
  }
 catch (  Exception e) {
    AQUtility.report(e);
  }
}
 

Example 24

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

Source file: MapMaker.java

  15 
vote

/** 
 * Specifies that each entry should be automatically removed from the map once a fixed duration has passed since the entry's creation.
 * @param duration the length of time after an entry is created that itshould be automatically removed
 * @param unit the unit that {@code duration} is expressed in
 * @throws IllegalArgumentException if {@code duration} is not positive
 * @throws IllegalStateException if the expiration time was already set
 */
public MapMaker expiration(long duration,TimeUnit unit){
  if (expirationNanos != 0) {
    throw new IllegalStateException("expiration time of " + expirationNanos + " ns was already set");
  }
  if (duration <= 0) {
    throw new IllegalArgumentException("invalid duration: " + duration);
  }
  this.expirationNanos=unit.toNanos(duration);
  useCustomMap=true;
  return this;
}
 

Example 25

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 26

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/server/.

Source file: AndroidNativeDriver.java

  15 
vote

@Override public Timeouts implicitlyWait(long time,TimeUnit unit){
  Preconditions.checkArgument(time > 0,"time argument should be greater than 0");
  long timeoutInMillis=TimeUnit.MILLISECONDS.convert(Math.max(0,time),unit);
  getWait().setTimeoutInMillis(timeoutInMillis);
  return this;
}
 

Example 27

From project archaius, under directory /archaius-core/src/main/java/com/netflix/config/.

Source file: FixedDelayPollingScheduler.java

  15 
vote

/** 
 * This method is implemented with  {@link java.util.concurrent.ScheduledExecutorService#scheduleWithFixedDelay(Runnable,long,long,TimeUnit)}
 */
@Override protected synchronized void schedule(Runnable runnable){
  executor=Executors.newScheduledThreadPool(1,new ThreadFactory(){
    @Override public Thread newThread(    Runnable r){
      Thread t=new Thread(r,"pollingConfigurationSource");
      t.setDaemon(true);
      return t;
    }
  }
);
  executor.scheduleWithFixedDelay(runnable,initialDelayMillis,delayMillis,TimeUnit.MILLISECONDS);
}
 

Example 28

From project ardverk-commons, under directory /src/main/java/org/ardverk/io/.

Source file: IdleInputStream.java

  15 
vote

public IdleInputStream(InputStream in,IdleCallback callback,long initialDelay,final long delay,final TimeUnit unit){
  super(in,callback);
  Runnable task=new Runnable(){
    private final long timeoutInMillis=unit.toMillis(delay);
    @Override public void run(){
      long time=System.currentTimeMillis() - timeStamp;
      if (time >= timeoutInMillis) {
        idle(time,TimeUnit.MILLISECONDS);
      }
    }
  }
;
  this.future=EXECUTOR.scheduleWithFixedDelay(task,initialDelay,delay,unit);
}
 

Example 29

From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/config/.

Source file: ConfigUtils.java

  15 
vote

/** 
 * Returns the sum of the  {@link Config}'s operation timeouts  in the given  {@link TimeUnit}.
 */
public static long getOperationTimeout(Config[] configs,TimeUnit unit){
  long time=0;
  for (  Config config : configs) {
    time+=config.getOperationTimeout(unit);
  }
  return time;
}