Java Code Examples for java.util.concurrent.TimeUnit#sleep()

The following examples show how to use java.util.concurrent.TimeUnit#sleep() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Eventually.java    From light-eventuate-4j with Apache License 2.0 6 votes vote down vote up
public static <T>  T eventuallyReturning(int iterations, int timeout, TimeUnit timeUnit, Supplier<T> body) {
  Throwable t = null;
  for (int i = 0; i < iterations; i++) {
    try {
      System.out.println("trying");
      return body.get();
    } catch (Throwable t1) {
      t = t1;
      try {
        timeUnit.sleep(timeout);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
  }
  throw new EventuallyException(String.format("Failed after %s iterations every %s milliseconds", iterations, 250), t);
}
 
Example 2
Source File: SfxMetrics.java    From signalfx-java with Apache License 2.0 6 votes vote down vote up
/**
 * Execute, with retries and tracking, the execution of the given {@link Callable}.
 *
 * @param function
 *         The {@link Callable} to execute.
 * @param maxRetries
 *         The maximum number of retries of the execution.
 * @param delay
 *         How long to wait between retries.
 * @param unit
 *         The unit of the retry delay.
 * @param metricPrefix
 *         A prefix for the metric names. Successes are counted by a "prefix.success" metric;
 *         failures by a "prefix.failure" metric, and the {@link Callable}'s execution is
 *         tracked by a "prefix.time" timer.
 * @param dimensions
 *         Additional dimension key/value pairs (an even number of strings must be provided).
 * @param <T>
 *         The return type of the {@link Callable}.
 * @return The return value of the {@link Callable}.
 */
public <T> T trackWithRetries(Callable<T> function, int maxRetries, long delay, TimeUnit unit,
                              String metricPrefix, String... dimensions) {
    int retryCounter = 0;
    while (true) {
        try {
            return track(function, metricPrefix, dimensions);
        } catch (RuntimeException ex) {
            counter(metricPrefix + ".retries", dimensions).inc();
            retryCounter++;
            if (retryCounter > maxRetries) {
                counter(metricPrefix + ".maxRetriesReached", dimensions).inc();
                throw ex;
            }
            try {
                unit.sleep(delay);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
        }
    }
}
 
Example 3
Source File: GelfSenderThread.java    From gelfclient with Apache License 2.0 6 votes vote down vote up
/***
 * Block and wait for all messages in the queue to send until the indicated {@code waitDuration}, {@code timeUnit} and
 * {@code retries} have elapsed. Each retry waits for the indicated {@code waitDuration} and {@code timeUnit} again.
 * @param waitDuration the wait duration.
 * @param timeUnit the time unit for the {@code waitDuration}.
 * @param retries the number of times to retry and wait for messages to flush.
 */
void flushSynchronously(int waitDuration, TimeUnit timeUnit, int retries) {

    LOG.debug("Attempting to flush messages in [{}/{}] with [{}] retries", waitDuration, timeUnit, retries);

    for (int i = 0; i <= retries; i++) {
        if (!flushingInProgress()) {
            LOG.debug("Successfully flushed messages. Shutting down now.");
            return;
        }

        LOG.debug("Flushing in progress. [{}] messages are still enqueued, and [{}] messages are still in-flight.",
                  queue.size(), inflightSends.get());

        try {
            timeUnit.sleep(waitDuration);
        } catch (InterruptedException e) {
            LOG.error("Interrupted message flushing during shutdown after [{}}] attempts.", i);
            Thread.currentThread().interrupt();
            return;
        }
    }
    LOG.error("Failed to flush messages in [{}] attempts. Shutting down anyway.", retries);
}
 
Example 4
Source File: AbstractEvent.java    From DBus with Apache License 2.0 5 votes vote down vote up
protected void sleep(long t, TimeUnit tu) {
    try {
        tu.sleep(t);
    } catch (InterruptedException e) {
        LOG.info("[control-event] 线程sleep:" + t + " " + tu.name() + "中被中断!");
    }
}
 
Example 5
Source File: ListenerTest.java    From sse-eventbus with Apache License 2.0 5 votes vote down vote up
private static void sleep(long value, TimeUnit timeUnit) {
	try {
		timeUnit.sleep(value);
	}
	catch (InterruptedException e) {
		// nothing here
	}
}
 
Example 6
Source File: ArrayMonitorDemo.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
static void serve(final String name, final TimeUnit update, final long delay)
{
    try
    {
        final PVAServer server = new PVAServer();

        final PVATimeStamp time = new PVATimeStamp();
        final PVADoubleArray value = new PVADoubleArray("value");
        final PVAStructure data = new PVAStructure("demo", "demo_t",
                                                   value,
                                                   time);
        final ServerPV pv = server.createPV(name, data);
        double number = 1.0;
        while (true)
        {
            update.sleep(delay);
            ++number;
            final double[] array = new double[1000000];
            for (int i=0; i<array.length; ++i)
                array[i] = number + 0.1 * i;
            value.set(array);
            time.set(Instant.now());
            pv.update(data);
        }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
 
Example 7
Source File: ScrollVersionsConfluenceServiceIntegrationTest.java    From maven-confluence-plugin with Apache License 2.0 5 votes vote down vote up
private static CompletableFuture<Void> sleep( TimeUnit timeunit, long unit ) {
    val result = new CompletableFuture<Void>();
    try {
        timeunit.sleep( unit);
        result.complete(null);
    }
    catch( InterruptedException ex ) {
        result.completeExceptionally(ex);
    }
    return result;

}
 
Example 8
Source File: ITUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static void forceWait(TimeUnit timeUnit, long timeout) {
  try {
    timeUnit.sleep(timeout);
  } catch (InterruptedException e) {
    // eat the exception
  }
}
 
Example 9
Source File: KafkaConsumerContainer.java    From DBus with Apache License 2.0 5 votes vote down vote up
private void sleep(long t, TimeUnit tu) {
    try {
        tu.sleep(t);
    } catch (InterruptedException e) {
        LoggerFactory.getLogger().error("[kafka-consumer-container] 线程sleep:" + t + " " + tu.name() + "中被中断!");
    }
}
 
Example 10
Source File: ThreadUtil.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Thread sleep
 *
 * @param timeUnit TimeUnit
 * @param timeout timeout
 */
public static void sleep(TimeUnit timeUnit, long timeout) {
	try {
		timeUnit.sleep(timeout);
	} catch (InterruptedException e) {
		Thread.currentThread().interrupt();
	}
}
 
Example 11
Source File: ThreadUtils.java    From oxygen with Apache License 2.0 5 votes vote down vote up
/**
 * 线程sleep等待
 *
 * @param time 时间
 * @param unit 单位
 */
public void sleep(long time, TimeUnit unit) {
  try {
    unit.sleep(time);
  } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
  }
}
 
Example 12
Source File: TimeIntervalLimiterTest.java    From vjtools with Apache License 2.0 5 votes vote down vote up
@Test
public void testTryAcquire() throws Exception {
	int interval = 100;
	TimeUnit timeUnit = TimeUnit.MILLISECONDS;

	TimeIntervalLimiter limiter = Concurrents.timeIntervalLimiter(interval, timeUnit);

	assertThat(limiter.tryAcquire()).isTrue();
	assertThat(limiter.tryAcquire()).isFalse();

	timeUnit.sleep(interval);
	assertThat(limiter.tryAcquire()).isTrue();
}
 
Example 13
Source File: TEnv.java    From Voovan with Apache License 2.0 5 votes vote down vote up
/**
 * 休眠函数
 * @param timeUnit 休眠时间单位
 * @param sleepTime 休眠时间
 * @return true: 超时结束, false: sleep 被打断
 */
public static boolean sleep(TimeUnit timeUnit, int sleepTime) {
	try {
		timeUnit.sleep(sleepTime);
		return true;
	} catch (InterruptedException e) {
		return false;
	}
}
 
Example 14
Source File: SseEventBusTest.java    From sse-eventbus with Apache License 2.0 5 votes vote down vote up
private static void sleep(long value, TimeUnit timeUnit) {
	try {
		timeUnit.sleep(value);
	}
	catch (InterruptedException e) {
		// nothing here
	}
}
 
Example 15
Source File: ThreadUtils.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * 不抛异常的sleep
 *
 * @author sxp
 * @since 2019/11/13
 */
public static void sleepQuietly(TimeUnit unit, long duration) {
  try {
    unit.sleep(duration);
  } catch (InterruptedException e) {
    //ignore
  }
}
 
Example 16
Source File: EchoCallbackHandler.java    From restfbmessenger with Apache License 2.0 4 votes vote down vote up
private void sleep(TimeUnit timeUnit, long duration) {
    try {
        timeUnit.sleep(duration);
    } catch (InterruptedException ignore) {
    }
}
 
Example 17
Source File: EchoCallbackHandler.java    From restfbmessenger with Apache License 2.0 4 votes vote down vote up
private void sleep(TimeUnit timeUnit, long duration) {
    try {
        timeUnit.sleep(duration);
    } catch (InterruptedException ignore) {
    }
}
 
Example 18
Source File: TestAsyncClusterAdminApi2.java    From hbase with Apache License 2.0 4 votes vote down vote up
private void trySleep(long timeout, TimeUnit unit) {
  try {
    unit.sleep(timeout);
  } catch (InterruptedException e) {
  }
}
 
Example 19
Source File: EchoCallbackHandler.java    From restfbmessenger with Apache License 2.0 4 votes vote down vote up
private void sleep(TimeUnit timeUnit, long duration) {
    try {
        timeUnit.sleep(duration);
    } catch (InterruptedException ignore) {
    }
}
 
Example 20
Source File: RestAction.java    From JDA with Apache License 2.0 3 votes vote down vote up
/**
 * Blocks the current Thread for the specified delay and calls {@link #complete()}
 * when delay has been reached.
 * <br>If the specified delay is negative this action will execute immediately. (see: {@link TimeUnit#sleep(long)})
 *
 * @param  delay
 *         The delay after which to execute a call to {@link #complete()}
 * @param  unit
 *         The {@link java.util.concurrent.TimeUnit TimeUnit} which should be used
 *         (this will use {@link java.util.concurrent.TimeUnit#sleep(long) unit.sleep(delay)})
 *
 * @throws java.lang.IllegalArgumentException
 *         If the specified {@link java.util.concurrent.TimeUnit TimeUnit} is {@code null}
 * @throws java.lang.RuntimeException
 *         If the sleep operation is interrupted
 *
 * @return The response value
 */
default T completeAfter(long delay, @Nonnull TimeUnit unit)
{
    Checks.notNull(unit, "TimeUnit");
    try
    {
        unit.sleep(delay);
        return complete();
    }
    catch (InterruptedException e)
    {
        throw new RuntimeException(e);
    }
}