Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing & superficial code changes

...

Operator

Overflow

 

Operator

Overflow

 

Operator

Overflow

 

Operator

Overflow

+

yes

 

-=

yes

 

<<

no

 

<

no

-

yes

 

*=

yes

 

>>

no

 

>

no

*

yes

 

/=

yes

 

&

no

 

>=

no

/

yes

 

%=

no

 

\

no

 

<=

no

%

no

 

<<=

no

 

^

no

 

==

no

++

yes

 

>>=

no

 

~

no

 

!=

no

--

yes

 

&=

no

 

!

no

 

&&

no

=

no

 

|=

no

 

un +

no

 

||

no

+=

yes

 

^=

no

 

un -

yes

 

?:

no

Wiki Markup
Failure to account for integer overflow has resulted in failures of real systems, for example, when implementing the {{compareTo()}} method. The meaning of the return value of the {{compareTo()}} method is defined only in terms of its sign and whether it is zero; the magnitude of the return value is irrelevant. Consequently, an apparent but incorrect optimization would be to subtract the operands and return the result. For operands of opposite signs, this can result in integer overflow, consequently violating the {{compareTo()}} contract \[[Bloch 2008, Item 12|AA. Bibliography#Bloch 08]\].

...

  • Pre-condition testing of the inputs. Check the inputs to each arithmetic operator to ensure that overflow cannot occur. Throw an ArithmeticException when the operation would overflow if it were performed; otherwise, perform the operation. We call this technique "Pre-condition the inputs" hereafter, for convenience.
  • Use a larger type and downcast. Cast the inputs to the next larger primitive integer type and perform the arithmetic in the larger size. Check each intermediate result for overflow of the original smaller type; , and throw an ArithmeticException if the range check fails. Note that the range check must be performed after each arithmetic operation. Downcast the final result to the original smaller type before assigning to the result variable. This approach cannot be use used for type long because long is already the largest primitive integer type.
  • Use BigInteger. Convert the inputs into objects of type BigInteger and perform all arithmetic using BigInteger methods. Throw an ArithmeticException if the final result is outside the range of the original smaller type; otherwise, convert back to the intended result type.

...

The "Use BigInteger" technique is conceptually the simplest of the three techniques. However, it requires the use of method calls for each operation in place of primitive arithmetic operators; this may obscure the intended meaning of the code. This technique will execute take more slowly time and will use more memory than the other techniques; performance degradation could be substantial.

Noncompliant Code Example

Pre-conditioning the Inputs

The following code example shows the necessary pre-conditioning checks required for each arithmetic operation on arguments of type int. The checks for the other integral types are analogous. In this example, we choose to throw an exception when integer overflow would occur; any other error handling is also acceptableEither arithmetic operation in this noncompliant code example could produce a result that overflows the range representable by type int. When overflow occurs, the result will be incorrect.

Code Block
bgColor#FFcccc#ccccff
publicstatic intfinal multAccumpreAdd(int oldAccleft, int newVal,right) intthrows scale)ArithmeticException {
  // May result in overflow 
  return oldAcc + (newVal * scale);
}

Compliant Solution (Pre-Condition the Inputs)

The code example below shows the necessary pre-conditioning checks required for each arithmetic operation on arguments of type int. The checks for the other integral types are analogous. In this example, we choose (for simplicity) to throw an exception when integer overflow would occur; any other appropriate error handling is also acceptable.

Code Block

static final preAdd(int left, int right) throws  if (right > 0 ? left > Integer.MAX_VALUE - right : left < Integer.MIN_VALUE - right) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preSubtract(int left, int right) throws ArithmeticException {
   if (right > 0 ? left >< Integer.MAXMIN_VALUE -+ right : left <> Integer.MINMAX_VALUE -+ right) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preSubtractpreMultiply(int left, int right) throws ArithmeticException {
  if (right > 0right>0 ? left <> Integer.MINMAX_VALUE/right + right : || left >< Integer.MAXMIN_VALUE + /right) {:
    throw  new ArithmeticException("Integer overflow");
  }
}

static final preMultiply(int left, int right) throws ArithmeticException {
  if (right>0 ? left > Integer.MAX_VALUE/right || left <right<-1 ? left > Integer.MIN_VALUE/right || left < Integer.MAX_VALUE/right :
         right == -1 && left == Integer.MIN_VALUE/right :) ) {
    throw new  (right<-1 ? left > Integer.MIN_VALUE/right || left < Integer.MAX_VALUE/right :
         right == -1 && left == Integer.MIN_VALUE) ArithmeticException("Integer overflow");
  }
}

static final preDivide(int left, int right) throws ArithmeticException {
  if ((left == Integer.MIN_VALUE) && (right == -1)) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preDividepreAbs(int left, int righta) throws ArithmeticException {
  if ((lefta == Integer.MIN_VALUE) {
 && (right == -1)) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preAbspreNegate(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preNegate(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
}

_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
}

These checks can be simplified when the original type is char. Because the range of type char includes only positive values, all comparisons with negative values may be omitted.

Noncompliant Code Example

Either operation in this noncompliant code example could produce a result that overflows the range of int. When overflow occurs, the result will be incorrect.

Code Block
bgColor#FFcccc

public int multAccum(int oldAcc, int newVal, int scale) {
  // May result in overflow 
  return oldAcc + (newVal * scale);
}

Compliant Solution (Pre-Condition the Inputs)

This compliant solution uses the preAdd() and preMultiply() methods defined above to indicate errors if the corresponding operations might overflowNote that although these pre-conditioning checks are correct, more efficient code could be possible. Also, the checks can be simplified when the original type is char. Because the range of type char includes only positive values, all comparisons with negative values may be omitted.

Code Block
bgColor#ccccff
public int multAccum(int oldAcc, int newVal, int scale) throws ArithmeticException {
  preMultiply(newVal, Scale);
  final int temp = newVal * scale;
  preAdd(oldAcc, temp);
  return oldAcc + temp;
}

...

For all integral types other than long, the next larger integral type can represent the result of any single integral operation. For example, operations on values of type int can be safely performed using type long. Therefore, we can perform an operation using the larger type and range-check before downcasting to the original type. Note, however, that this guarantee holds only for a one single arithmetic operation; larger expressions without per-operation bounds checks checking may overflow the larger type.

...

This compliant solution shows the implementation of a method for checking whether a long value falls within the representable range of they an int. The implementations of range checks for the smaller primitive integer types are exactly analogoussimilar.

Code Block
bgColor#ccccff

public long intRangeCheck(long value) throws ArithmeticOverflow {
  if ((value < Integer.MIN_VALUE) || (value > Integer.MAX_VALUE)) {
    throw new ArithmeticException("Integer overflow");
  }
  return value;
}

public int multAccum(int oldAcc, int newVal, int scale) throws ArithmeticException {
  final long res = 
    intRangeCheck(((long) oldAcc) + intRangeCheck((long) newVal * (long) scale));
  return (int) res; // safe down-cast
}

...

Type BigInteger is the standard arbitrary-precision integer type provided by the Java standard libraries. The arithmetic operations implemented as methods of this type cannot themselves overflow; instead, they produce the numerically correct result. As a consequence, compliant code performs only a single range check—just before converting the final result to the original smaller type. This property provides conceptual simplicity. An unfortunate consequence of this technique is that compliant code must be written using method calls in place instead of primitive arithmetic operators; this can obscure the intent of the code. Note that operations Operations on objects of type BigInteger can also be significantly less efficient than operations on the original primitive integer type. Whether this loss of efficiency is important will depend on the context in which the code is usedthan operations on the original primitive integer type.

Code Block
bgColor#ccccff
private static final BigInteger bigMaxLongbigMaxInt = BigInteger.valueOf(LongInt.MAX_VALUE);
private static final BigInteger bigMinLongbigMinInt = BigInteger.valueOf(LongInt.MIN_VALUE);

public BigInteger longRangeCheckintRangeCheck(BigInteger val) throws ArithmeticException {
  if (val.compareTo(bigMaxLongbigMaxInt) == 1 ||
          val.compareTo(bigMinLongbigMinInt) == -1) {
    throw new ArithmeticException("Integer overflow");
  }
  return val;
}

public longint multAccum(longint oldAcc, longint newVal, longint scale) throws ArithmeticException { 
  BigInteger product =
    BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale));
  BigInteger res = longRangeCheckintRangeCheck(BigInteger.valueOf(oldAcc).add(product));
  return res.longValueintValue(); // safe conversion
}

Noncompliant Code Example AtomicInteger

Operations on objects of type AtomicInteger suffer from the same overflow issues as do the other integer types. The solutions are generally similar to those shown above; however, concurrency issues add additional complications. First, avoid possible potential issues with time-of-check-time-of-use must be avoided. (See guidleine VNA02-J. Ensure that compound operations on shared variables are atomic for more information). Secondly, use of an AtomicInteger creates happens-before relationships between the various threads that access it. Consequently, changes to the number or order of accesses may alter the execution of the overall program. In such cases you must either choose to accept the altered execution or carefully craft the implementation of your compliant technique to preserve the exact number and order of accesses to the AtomicInteger.

...

Code Block
bgColor#FFcccc
class InventoryManager {
  private final AtomicInteger itemsInInventory = new AtomicInteger(100);

  //...
  public final void returnItemnextItem() {
    itemsInInventory++;
  }
} 

...

Code Block
bgColor#ccccff
class InventoryManager {
  private final AtomicInteger itemsInInventory = new AtomicInteger(100);

  public final void returnItemnextItem() {
    while (true) {
      int old = itemsInInventory.get();
      if (old == Integer.MAX_VALUE) {
        throw new ArithmeticException("Integer overflow");
      }
      int next = old + 1; // Increment
      if (itemsInInventory.compareAndSet(old, next)) {
        break;
      }
    } // end while
  } // end removeItem()
}

Wiki Markup
The arguments to the {{compareAndSet()}} method are the expected value of the variable when the method is invoked and the intended new value. The variable's value is updated if, and only if, the current value and the expected value are equal (see \[[API 2006|AA. Bibliography#API 06]\] class [{{AtomicInteger}}|http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html]). Refer to guideline [VNA02-J. Ensure that compound operations on shared variables are atomic] for more details.

...

INT00-EX1: Depending on circumstances, integer overflow could be benign. For instance, the Object.hashcode() method could return all representable values of type int; further. Furthermore, many algorithms for computing hashcodes intentionally allow overflow to occur.

INT00-EX2: The added complexity and cost of programmer-written overflow checks may exceed their value for all but the most - critical code. In such cases, consider the alternative of treating integral values as though they are tainted data, using appropriate range checks as the notional sanitizing code. These range checks should ensure that incoming values cannot cause integer overflow. Note that sound determination of allowable ranges may require deep understanding of the details of the code protected by the range checks; correct determination of the allowable ranges may be extremely difficult.

...