Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Programs must not allow mathematical operations to exceed the integer ranges provided by their primitive integer data types. According to the The Java Language Specification (JLS), §4.2.2, "Integer Operations" [JLS 2005]:

...

Because the ranges of Java types are not symmetric (the negation of each minimum value is one more than each maximum value), even operations such as unary negation can overflow if applied to a minimum value. Because the java.lang.math.abs() method returns the absolute value of any number, it can also overflow if given the minimum int or long as an argument.

...

Comparison of Compliant Techniques

...

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

...

The two 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 only when the current value and the expected value are equal [API 2006] (refer to rule VNA02-J. Ensure that compound operations on shared variables are atomic for more details).

...

NUM00-EX1: Prevention of integer overflow is unnecessary for numeric fields that undergo bitwise operations and not arithmetic operations (see rule NUM01-J. Do not perform bitwise and arithmetic operations on the same data for more information).

...

...

[API 2006]

Class AtomicInteger

[Bloch 2005]

Puzzle 27, "Shifty i's"

[Bloch 2008]Item 12, "Minimize the Accessibility of Classes and Members"

[JLS 2005]

§4.2.2, "Integer Operations"
§15.22, "Bitwise and Logical Operators"

[Seacord 2005]

Chapter 5, "Integers"

[Seacord 2015]Image result for video icon IDS17-J. Prevent XML External Entity Attacks LiveLesson

[Tutorials 2008]

Primitive Data Types

...