@Override protected Duration computeNextWaitTime() { Duration next = mNextSleep; mNextSleep = mNextSleep.multipliedBy(2); if (mNextSleep.compareTo(mMaxSleep) > 0) { mNextSleep = mMaxSleep; } // Add jitter. long jitter = Math.round(ThreadLocalRandom.current().nextDouble(0.1) * next.toMillis()); return next.plusMillis(jitter); }
private void execute(PrimitiveOperation operation, int attemptIndex, CompletableFuture<byte[]> future) { session.execute(operation).whenComplete((r, e) -> { if (e != null) { if (attemptIndex < maxRetries + 1 && retryableCheck.test(Throwables.getRootCause(e))) { log.debug("Retry attempt ({} of {}). Failure due to {}", attemptIndex, maxRetries, Throwables.getRootCause(e).getClass()); scheduler.schedule(delayBetweenRetries.multipliedBy(2 ^ attemptIndex), () -> execute(operation, attemptIndex + 1, future)); } else { future.completeExceptionally(e); } } else { future.complete(r); } }); } }
/** * Builds a new recurring policy. * * @return the new instance */ public RecurringPolicy build() { Duration min = this.min == null ? interval.dividedBy(10) : this.min; Duration max = this.max == null ? interval.multipliedBy(5) : this.max; BiFunction<Duration, Integer, Duration> lengthenFunction = this.lengthenFunction == null ? DEFAULT_LENGTHEN : this.lengthenFunction; BiFunction<Duration, Integer, Duration> shortenFunction = this.shortenFunction == null ? DEFAULT_SHORTEN : this.shortenFunction; return new ScheduledPollingStrategy.AdaptiveRecurringPolicy(min, interval, max, shortenFunction, lengthenFunction); }
break; waitTime = pertubateTime(waitTime.multipliedBy(2));
break; waitTime = pertubTime(waitTime.multipliedBy(2));
/** * Requests a probe of the given suspect from the given member. * * @param member the member to perform the probe * @param suspect the suspect member to probe */ private CompletableFuture<Boolean> requestProbe(SwimMember member, ImmutableMember suspect) { LOGGER.debug("{} - Requesting probe of {} from {}", this.localMember.id(), suspect, member); return bootstrapService.getMessagingService().sendAndReceive( member.address(), MEMBERSHIP_PROBE_REQUEST, SERIALIZER.encode(suspect), false, config.getProbeTimeout().multipliedBy(2)) .<Boolean>thenApply(SERIALIZER::decode) .<Boolean>exceptionally(e -> false) .thenApply(succeeded -> { LOGGER.debug("{} - Probe request of {} from {} {}", localMember.id(), suspect, member, succeeded ? "succeeded" : "failed"); return succeeded; }); }
nextBackoff = firstBackoff.multipliedBy((long) Math.pow(2, iteration)); if (nextBackoff.compareTo(maxBackoff) > 0) { nextBackoff = maxBackoff; jitterOffset = nextBackoff.multipliedBy((long) (100 * jitterFactor)) .dividedBy(100) .toMillis();
/** * Resets the join timer. */ private void resetJoinTimer() { cancelJoinTimer(); joinTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout().multipliedBy(2), () -> { join(getActiveMemberStates().iterator()); }); }
@Test public void testHaltingPredicateHonorsTimeRange() { // verify that halting predicate does nothing and changes no state if the // document's timestamp is outside of the time range. AtomicBoolean thisReaderNearEnd = new AtomicBoolean(false); AtomicBoolean otherReaderNearEnd = new AtomicBoolean(false); Duration duration = Duration.ofMinutes(5); ParallelHaltingPredicate parallelHaltingPredicate = new ParallelHaltingPredicate(thisReaderNearEnd, otherReaderNearEnd, duration); boolean testResult = parallelHaltingPredicate.accepts(createSourceRecordWithTimestamp(Instant.now().minus(duration.multipliedBy(2)))); Assert.assertTrue(testResult); Assert.assertFalse(thisReaderNearEnd.get()); Assert.assertFalse(otherReaderNearEnd.get()); }
backoffMS = Durations.min(backoffMS.multipliedBy(2), idApplicationWaitMS.multipliedBy(32)); log.warn("Temporary storage exception while acquiring id block - retrying in {}: {}", backoffMS, e); sleepAndConvertInterrupts(backoffMS);
Tile[][][] tiles = client.getScene().getTiles(); Instant expire = Instant.now().minus(HunterTrap.TRAP_TIME.multipliedBy(2));
backoffMS = Durations.min(backoffMS.multipliedBy(2), idApplicationWaitMS.multipliedBy(32)); log.warn("Temporary storage exception while acquiring id block - retrying in {}: {}", backoffMS, e); sleepAndConvertInterrupts(backoffMS);
@Test public void cacheIs10XFasterThanNonCached() { int iterations = 10; String password = new RandomValueStringGenerator().generate(); String encodedBcrypt = cachingPasswordEncoder.encode(password); PasswordEncoder nonCachingPasswordEncoder = cachingPasswordEncoder.getPasswordEncoder(); assertTrue(cachingPasswordEncoder.matches(password, encodedBcrypt)); // warm the cache Instant start = Instant.now(); for (int i = 0; i < iterations; i++) { assertTrue(nonCachingPasswordEncoder.matches(password, encodedBcrypt)); } Instant middle = Instant.now(); for (int i = 0; i < iterations; i++) { assertTrue(cachingPasswordEncoder.matches(password, encodedBcrypt)); } Instant end = Instant.now(); Duration bcryptTime = Duration.between(start, middle); Duration cacheTime = Duration.between(middle, end); assertThat( "cache wasn't fast enough (see ISO-8601 for understanding the strings)", cacheTime.multipliedBy(10L), is(lessThan(bcryptTime)) ); }
if (iterator.hasNext()) { cancelJoinTimer(); joinTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout().multipliedBy(2), () -> { join(iterator); });
private Duration getBackoffTimeWhenSweepHasNotRun() { return Duration.ofMillis(sweepPauseMillis.get()).plusSeconds(1).multipliedBy(20); // 2 minutes by default }
|| response.error().type() == RaftError.Type.NO_LEADER) { cancelConfigureTimer(); configureTimeout = cluster.getContext().getThreadContext().schedule(cluster.getContext().getElectionTimeout().multipliedBy(2), () -> configure(type, future)); } else { cancelConfigureTimer();
/** * Calculates the start and end timestamps that will be used when quering the metrics sources when doing the * canary judgements for each judgement interval. * * @param judgementNumber The judgement number / index for the canary analysis execution * @param judgementDuration The duration of the judgement window * @param config The execution request config * @return A wrapper object containing the start and end times to be used as Instants */ protected ScopeTimeConfig calculateStartAndEndForJudgement(CanaryAnalysisExecutionRequest config, long judgementNumber, Duration judgementDuration) { Duration warmupDuration = config.getBeginCanaryAnalysisAfterAsDuration(); Duration offset = judgementDuration.multipliedBy(judgementNumber); ScopeTimeConfig scopeTimeConfig = new ScopeTimeConfig(); Instant startTime = Optional.ofNullable(config.getStartTime()).orElse(now(clock)); scopeTimeConfig.start = startTime; scopeTimeConfig.end = startTime.plus(offset); if (config.getEndTime() == null) { scopeTimeConfig.start = scopeTimeConfig.start.plus(warmupDuration); scopeTimeConfig.end = scopeTimeConfig.end.plus(warmupDuration); } // If the look back is defined, use it to recalculate the start time, this is used to do sliding window judgements if (config.getLookBackAsInstant().isAfter(ZERO_AS_INSTANT)) { scopeTimeConfig.start = scopeTimeConfig.end.minus(config.getLookBackAsDuration()); } return scopeTimeConfig; }
@Test public void canConfigureRefreshInterval() { Duration doubleRefreshInterval = REFRESH_INTERVAL.multipliedBy(2L); AtomicLong atomicLong = new AtomicLong(); PollingRefreshable<Long> lessFrequentlyPollingRefreshable = PollingRefreshable.createWithSpecificPoller( atomicLong::incrementAndGet, doubleRefreshInterval, scheduler); Refreshable<Long> refreshable = lessFrequentlyPollingRefreshable.getRefreshable(); assertRefreshableContainsAndClear(refreshable, 1L); // This is only about half of our poller's refresh interval, so we shouldn't have polled yet scheduler.tick(REFRESH_INTERVAL.toMillis() + 1, TimeUnit.MILLISECONDS); assertThat(refreshable.getAndClear()).isEmpty(); // But now we cumulatively have ticked by 2*REFRESH_INTERVAL + 1, so we should have polled scheduler.tick(REFRESH_INTERVAL.toMillis(), TimeUnit.MILLISECONDS); assertRefreshableContainsAndClear(refreshable, 2L); }
/** * Supports the multiplication operator; equivalent to calling the {@link Duration#multipliedBy(long)} method. * * @param self a Duration * @param scalar the value to multiply by * @return a Duration * @since 2.5.0 */ public static Duration multiply(final Duration self, long scalar) { return self.multipliedBy(scalar); }
/** * Resets the join timer. */ private void resetJoinTimer() { cancelJoinTimer(); joinTimeout = context.getThreadContext().schedule(context.getElectionTimeout().multipliedBy(2), () -> { join(getActiveMemberStates().iterator()); }); }