List of usage examples for com.google.common.math LongMath checkedAdd
@GwtIncompatible("TODO") public static long checkedAdd(long a, long b)
From source file:com.google.errorprone.bugpatterns.ConstantOverflow.java
static Long binop(Kind kind, long lhs, long rhs) { switch (kind) { case MULTIPLY: return LongMath.checkedMultiply(lhs, rhs); case DIVIDE://from ww w .ja va2 s .c o m return lhs / rhs; case REMAINDER: return lhs % rhs; case PLUS: return LongMath.checkedAdd(lhs, rhs); case MINUS: return LongMath.checkedSubtract(lhs, rhs); case LEFT_SHIFT: return lhs << rhs; case RIGHT_SHIFT: return lhs >> rhs; case UNSIGNED_RIGHT_SHIFT: return lhs >>> rhs; case AND: return lhs & rhs; case XOR: return lhs ^ rhs; case OR: return lhs | rhs; default: return null; } }
From source file:org.apache.phoenix.schema.Sequence.java
private long increment(SequenceValue value, ValueOp op, long numToAllocate) throws SQLException { boolean increasingSeq = value.incrementBy > 0 && op != ValueOp.VALIDATE_SEQUENCE; // check if the the sequence has already reached the min/max limit if (value.limitReached && op != ValueOp.VALIDATE_SEQUENCE) { if (value.cycle) { value.limitReached = false;//from w w w.java2 s . co m throw EMPTY_SEQUENCE_CACHE_EXCEPTION; } else { SQLExceptionCode code = increasingSeq ? SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE : SQLExceptionCode.SEQUENCE_VAL_REACHED_MIN_VALUE; throw SequenceUtil.getException(this.key.getSchemaName(), this.key.getSequenceName(), code); } } long returnValue = value.currentValue; if (op == ValueOp.INCREMENT_SEQUENCE) { boolean overflowOrUnderflow = false; // advance currentValue while checking for overflow try { // advance by numToAllocate * the increment amount value.currentValue = LongMath.checkedAdd(value.currentValue, numToAllocate * value.incrementBy); } catch (ArithmeticException e) { overflowOrUnderflow = true; } // set the limitReached flag (which will be checked the next time increment is called) // if overflow or limit was reached if (overflowOrUnderflow || (increasingSeq && value.currentValue > value.maxValue) || (!increasingSeq && value.currentValue < value.minValue)) { value.limitReached = true; } } return returnValue; }
From source file:org.sfs.block.RecyclingAllocator.java
protected long computeLast(long first, long length) { return LongMath.checkedAdd(first, Rounding.up(length, blockSize)) - 1; }
From source file:com.duprasville.guava.probably.BloomFilter.java
/** * Combines {@code this} filter with another compatible filter. The mutations happen to {@code * this} instance. Callers must ensure {@code this} filter is appropriately sized to avoid * saturating it or running out of space. * * @param f filter to be combined into {@code this} filter - {@code f} is not mutated * @return {@code true} if the operation was successful, {@code false} otherwise * @throws NullPointerException if the specified filter is null * @throws IllegalArgumentException if {@link #isCompatible(ProbabilisticFilter)} {@code == * false} * @see #add(Object)/*from w w w . j a v a2 s .c o m*/ * @see #addAll(Collection) * @see #contains(Object) */ public boolean addAll(ProbabilisticFilter<E> f) { checkNotNull(f); checkArgument(this != f, "Cannot combine a " + this.getClass().getSimpleName() + " with itself."); checkArgument(f instanceof BloomFilter, "Cannot combine a " + this.getClass().getSimpleName() + " with a " + f.getClass().getSimpleName()); checkArgument(this.isCompatible(f), "Cannot combine incompatible filters. " + this.getClass().getSimpleName() + " instances must have equivalent funnels; the same " + "strategy; and the same number of buckets, entries per bucket, and bits per entry."); delegate.putAll(((BloomFilter<E>) f).delegate); size = LongMath.checkedAdd(size, f.sizeLong()); return true; }
From source file:org.apache.phoenix.schema.Sequence.java
/** * This method checks whether there are sufficient values in the SequenceValue * cached on the client to allocate the requested number of slots. It handles * decreasing and increasing sequences as well as any overflows or underflows * encountered./*w w w. j a v a2 s . c om*/ */ private boolean isSequenceCacheExhaustedForBulkAllocation(final long numToAllocate, final SequenceValue value) throws SQLException { long targetSequenceValue; performValidationForBulkAllocation(numToAllocate, value); try { targetSequenceValue = LongMath.checkedAdd(value.currentValue, numToAllocate * value.incrementBy); } catch (ArithmeticException e) { // Perform a CheckedAdd to make sure if over/underflow // We don't treat this as the cache being exhausted as the current value may be valid in the case // of no cycle, logic in increment() will take care of detecting we've hit the limit of the sequence return false; } if (value.incrementBy > 0) { return targetSequenceValue > value.nextValue; } else { return targetSequenceValue < value.nextValue; } }
From source file:org.kitesdk.morphline.solr.SmoothRateLimiter.java
@Override final long reserveEarliestAvailable(int requiredPermits, long nowMicros) { resync(nowMicros);//from w w w .jav a 2 s . c o m long returnValue = nextFreeTicketMicros; double storedPermitsToSpend = min(requiredPermits, this.storedPermits); double freshPermits = requiredPermits - storedPermitsToSpend; long waitMicros = storedPermitsToWaitTime(this.storedPermits, storedPermitsToSpend) + (long) (freshPermits * stableIntervalMicros); try { this.nextFreeTicketMicros = LongMath.checkedAdd(nextFreeTicketMicros, waitMicros); } catch (ArithmeticException e) { this.nextFreeTicketMicros = Long.MAX_VALUE; } this.storedPermits -= storedPermitsToSpend; return returnValue; }
From source file:org.apache.impala.planner.PlanNode.java
/** * Computes and returns the sum of two cardinalities. If an overflow occurs, * the maximum Long value is returned (Long.MAX_VALUE). *//*from www. j a v a2 s .co m*/ public static long addCardinalities(long a, long b) { try { return LongMath.checkedAdd(a, b); } catch (ArithmeticException e) { LOG.warn("overflow when adding cardinalities: " + a + ", " + b); return Long.MAX_VALUE; } }
From source file:org.sfs.filesystem.volume.VolumeV1.java
@Override public Observable<Optional<ReadStreamBlob>> getDataStream(SfsVertx vertx, final long position, final Optional<Long> oOffset, final Optional<Long> oLength) { return Defer.aVoid().doOnNext(aVoid -> checkStarted()) .flatMap(aVoid -> RangeLock.lockedObservable(vertx, () -> indexFile.tryReadLock(position, indexBlockSize), () -> getIndexBlock0(vertx, position), LOCK_WAIT_TIMEOUT)) .filter(Optional::isPresent).map(Optional::get) .filter(positional -> !positional.getValue().getGarbageCollected()) .filter(positional -> !positional.getValue().getDeleted()).flatMap(positional -> { XVolume.XIndexBlock header = positional.getValue(); long dataPosition = header.getDataPosition(); long dataLength = header.getDataLength(); long startPosition; if (oOffset.isPresent()) { long offset = oOffset.get(); startPosition = offset <= 0 ? dataPosition : LongMath.checkedAdd(dataPosition, offset); } else { startPosition = dataPosition; }// w ww .j a v a 2s.c om long normalizedLength; if (oLength.isPresent()) { long length = oLength.get(); normalizedLength = length <= -1 ? dataLength : Math.min(dataLength, length); } else { normalizedLength = dataLength; } long endPosition = LongMath.checkedAdd(dataPosition, dataLength); if (startPosition >= endPosition) { Preconditions.checkState(startPosition <= endPosition, "Offset must be <= %s", endPosition - dataPosition); } ReadStreamBlob readStreamBlob = new ReadStreamBlob(volumeId, position, 0, normalizedLength) { @Override public Observable<Void> produce(BufferEndableWriteStream endableWriteStream) { return blobFile.produce(vertx, startPosition, normalizedLength, endableWriteStream) .onErrorResumeNext(throwable -> { Optional<RejectedExecutionException> oException = ExceptionHelper .unwrapCause(RejectedExecutionException.class, throwable); if (oException.isPresent()) { return Observable .error(new VolumeToBusyExecutionException(oException.get())); } else { return Observable.error(throwable); } }); } }; return Observable.just(Optional.of(readStreamBlob)); }).singleOrDefault(Optional.absent()).onErrorResumeNext(throwable -> { Optional<RejectedExecutionException> oException = ExceptionHelper .unwrapCause(RejectedExecutionException.class, throwable); if (oException.isPresent()) { return Observable.error(new VolumeToBusyExecutionException(oException.get())); } else { return Observable.error(throwable); } }); }
From source file:org.apache.hadoop.hive.ql.stats.StatsUtils.java
/** Bounded addition - overflows become MAX_VALUE */ public static long safeAdd(long a, long b) { try {/*from w ww . ja v a 2 s . c o m*/ return LongMath.checkedAdd(a, b); } catch (ArithmeticException ex) { return Long.MAX_VALUE; } }