public static boolean compareAndIncreaseOnly(final AtomicLong target, final long value) { long prev = target.get(); while (value > prev) { boolean updated = target.compareAndSet(prev, value); if (updated) return true; prev = target.get(); } return false; }
private boolean acquireLogPermission(String msg) { AtomicLong cooldown = mCooldowns.computeIfAbsent(msg, m -> new AtomicLong(0)); long allowed = cooldown.get(); long now = System.currentTimeMillis(); return now >= allowed && cooldown.compareAndSet(allowed, now + mCooldownMs); }
@Test(timeout = 2000) public void testUnsubscribeFromSynchronousInfiniteObservable() { final AtomicLong count = new AtomicLong(); INFINITE_OBSERVABLE.take(10).subscribe(new Consumer<Long>() { @Override public void accept(Long l) { count.set(l); } }); assertEquals(10, count.get()); }
@Test public void shouldRunWithDelay() throws Throwable { // Given life.start(); final AtomicLong runTime = new AtomicLong(); final CountDownLatch latch = new CountDownLatch( 1 ); long time = System.nanoTime(); scheduler.schedule( Group.INDEX_POPULATION, () -> { runTime.set( System.nanoTime() ); latch.countDown(); }, 100, TimeUnit.MILLISECONDS ); latch.await(); assertTrue( time + TimeUnit.MILLISECONDS.toNanos( 100 ) <= runTime.get() ); }
@Test public void prefetchIsUsed() { AtomicLong initialRequest = new AtomicLong(); StepVerifier.create(Flux.range(1, 10) .doOnRequest(r -> initialRequest.compareAndSet(0L, r)) .groupBy(i -> i % 5, 11) .concatMap(v -> v)) .expectNextCount(10) .verifyComplete(); assertThat(initialRequest.get()).isEqualTo(11); }
/** * Updates the value currently associated with {@code key} with the specified function, and * returns the old value. If there is not currently a value associated with {@code key}, the * function is applied to {@code 0L}. * * @since 21.0 */ @CanIgnoreReturnValue public long getAndUpdate(K key, LongUnaryOperator updaterFunction) { checkNotNull(updaterFunction); AtomicLong holder = new AtomicLong(); map.compute( key, (k, value) -> { long oldValue = (value == null) ? 0L : value.longValue(); holder.set(oldValue); return updaterFunction.applyAsLong(oldValue); }); return holder.get(); }
private Iterable<Pair<Integer,Long>> allNodeCounts( Function<String, Integer> labelTranslationTable, Map<String, AtomicLong> counts ) { Collection<Pair<Integer,Long>> result = new ArrayList<>(); for ( Map.Entry<String, AtomicLong> count : counts.entrySet() ) { result.add( Pair.of( labelTranslationTable.apply( count.getKey() ), count.getValue().get() ) ); } counts.put( null, new AtomicLong( counts.size() ) ); return result; }
public void testForEach() { ImmutableLongArray.of().forEach(i -> fail()); ImmutableLongArray.of(0, 1, 3).subArray(1, 1).forEach(i -> fail()); AtomicLong count = new AtomicLong(0); ImmutableLongArray.of(0, 1, 2, 3) .forEach(i -> assertThat(i).isEqualTo(count.getAndIncrement())); assertEquals(4, count.get()); }
@Override public void doMonitor(ServiceEmitter emitter) { final long priorCount = priorRequestCount.get(); final long totalCount = totalRequestCount.get(); final ServiceMetricEvent.Builder builder = ServiceMetricEvent.builder(); emitter.emit(builder.build("query/cache/redis/total/requests", totalCount)); emitter.emit(builder.build("query/cache/redis/delta/requests", totalCount - priorCount)); if (!priorRequestCount.compareAndSet(priorCount, totalCount)) { log.error("Prior value changed while I was reporting! updating anyways"); priorRequestCount.set(totalCount); } }
public Void call(JavaRDD<ApacheAccessLog> accessLogs) { Tuple4<Long, Long, Long, Long> stats = Functions.contentSizeStats(accessLogs); if (stats != null) { runningCount.getAndAdd(stats._1()); runningSum.getAndAdd(stats._2()); runningMin.set(Math.min(runningMin.get(), stats._3())); runningMax.set(Math.max(runningMax.get(), stats._4())); } return null; }} );
@Override public void onNext(T t) { long idx = index.get(); if (idx == Long.MAX_VALUE || !index.compareAndSet(idx, idx + 1)) { return; } Disposable d = task.get(); if (d != null) { d.dispose(); } downstream.onNext(t); ObservableSource<?> itemTimeoutObservableSource; try { itemTimeoutObservableSource = ObjectHelper.requireNonNull( itemTimeoutIndicator.apply(t), "The itemTimeoutIndicator returned a null ObservableSource."); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); upstream.get().dispose(); index.getAndSet(Long.MAX_VALUE); downstream.onError(ex); return; } TimeoutConsumer consumer = new TimeoutConsumer(idx + 1, this); if (task.replace(consumer)) { itemTimeoutObservableSource.subscribe(consumer); } }
@Test(timeout = 2000) public void testUnsubscribeFromSynchronousInfiniteFlowable() { final AtomicLong count = new AtomicLong(); INFINITE_OBSERVABLE.take(10).subscribe(new Consumer<Long>() { @Override public void accept(Long l) { count.set(l); } }); assertEquals(10, count.get()); }
@Test public void test() { final AtomicLong id = new AtomicLong(); final int ITERATIONS = 51; doInJPA( this::entityManagerFactory, entityManager -> { for ( int i = 1; i <= ITERATIONS; i++ ) { ApplicationConfiguration model = new ApplicationConfiguration(); entityManager.persist( model ); id.set( model.getId() ); } } ); assertEquals( ITERATIONS, id.get() ); }
public long getLevelMinPriority(int level, long taskThreadUsageNanos) { levelMinPriority[level].compareAndSet(-1, taskThreadUsageNanos); return levelMinPriority[level].get(); }
public RFuture<Boolean> tryLockAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId) { RPromise<Boolean> result = new RedissonPromise<Boolean>(); long newLeaseTime = -1; if (leaseTime != -1) { newLeaseTime = unit.toMillis(waitTime)*2; } AtomicLong time = new AtomicLong(System.currentTimeMillis()); AtomicLong remainTime = new AtomicLong(-1); if (waitTime != -1) { remainTime.set(unit.toMillis(waitTime)); } long lockWaitTime = calcLockWaitTime(remainTime.get()); AtomicInteger failedLocksLimit = new AtomicInteger(failedLocksLimit()); List<RLock> acquiredLocks = new ArrayList<RLock>(locks.size()); tryAcquireLockAsync(locks.listIterator(), acquiredLocks, result, lockWaitTime, waitTime, leaseTime, newLeaseTime, remainTime, time, failedLocksLimit, unit, threadId); return result; }
/** * If there's a bug in builder growth, we wouldn't know how to expose it. So, brute force the hell * out of it for a while and see what happens. */ public void testBuilder_bruteForce() { for (int i = 0; i < reduceIterationsIfGwt(100); i++) { ImmutableLongArray.Builder builder = ImmutableLongArray.builder(RANDOM.nextInt(20)); AtomicLong counter = new AtomicLong(0); while (counter.get() < 1000) { BuilderOp op = BuilderOp.randomOp(); op.doIt(builder, counter); } ImmutableLongArray iia = builder.build(); for (int j = 0; j < iia.length(); j++) { assertThat(iia.get(j)).isEqualTo((long) j); } } }
@Override public void onNext(T t) { long idx = index.get(); if (idx == Long.MAX_VALUE || !index.compareAndSet(idx, idx + 1)) { return; } Disposable d = task.get(); if (d != null) { d.dispose(); } consumed++; downstream.onNext(t); Publisher<?> itemTimeoutPublisher; try { itemTimeoutPublisher = ObjectHelper.requireNonNull( itemTimeoutIndicator.apply(t), "The itemTimeoutIndicator returned a null Publisher."); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); upstream.get().cancel(); index.getAndSet(Long.MAX_VALUE); downstream.onError(ex); return; } TimeoutConsumer consumer = new TimeoutConsumer(idx + 1, this); if (task.replace(consumer)) { itemTimeoutPublisher.subscribe(consumer); } }
@Test public void timer() { final TestScheduler testScheduler = new TestScheduler(); final AtomicLong atomicLong = new AtomicLong(); Single.timer(2, TimeUnit.SECONDS, testScheduler).subscribe(new Consumer<Long>() { @Override public void accept(final Long value) throws Exception { atomicLong.incrementAndGet(); } }); assertEquals(0, atomicLong.get()); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); assertEquals(0, atomicLong.get()); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); assertEquals(1, atomicLong.get()); } }