public static long clampAdd(long lhs, long rhs) {
    long sum = lhs + rhs;

    // From "Hacker's Delight", overflow occurs IFF both operands have the same sign and the
    // sign of the sum differs from the operands. Here we're doing a basic bitwise check that
    // collapses 6 branches down to 2. The expression {@code lhs ^ rhs} will have the high-order
    // bit set to true IFF the signs are different.
    if ((~(lhs ^ rhs) & (lhs ^ sum)) < 0) {
      if (lhs >= 0) {
        return Long.MAX_VALUE;
      } else {
        return Long.MIN_VALUE;
      }
    }

    return sum;
  }
Add the supplied arguments and handle overflow by clamping the resulting sum to
{@code Long.MinValue} if the sum would have been less than {@code Long.MinValue} or
{@code Long.MaxValue} if the sum would have been greater than {@code Long.MaxValue}.

@param lhs left hand side of sum
@param rhs right hand side of sum
@return the sum if no overflow occurs, or the clamped extreme if it does.
samza-core/src/main/java/org/apache/samza/util/MathUtil.java