Shiv Shiv - 1 month ago 13
Java Question

Is BigInteger Thread safe?

I have a requirement to update a global

BigInteger
value via multiple threads -- is
BigInteger
thread safe?

Answer

BigInteger objects are an representative example of immutable objects.
To put it simply:

Each immutable object is thread-safe, but the reference to it is not.

For immutable objects the state is fixed for an entire lifetime. Because there is no option to change it therefore each "change" operation is equivalent to replacement by a new object. So after series of modifications performed parallely by N threads on a specific reference the result value is hard to predict (some updates could be lost - unnoticed).
The same story is with Integer class. To overcome that limitation AtomicInteger class was introduced to JDK5.
Unfortunately there is no "AtomicBigInteger" class in JDK. The alternate solution is to wrap an object instance with AtomicReference - which works as a proxy that makes all operations synchronised and atomic.

I propose a following compact solution that requires JDK 8:

final AtomicReference<BigInteger> valueHolder = new AtomicReference(BigInteger.ZERO);

Using this approach any method provided by BigInteger could be restated as a lambda expression, e.g.:

valueHolder.updateAndGet(x -> x.add(BigInteger.valueOf(10)));

To check if the solution is correct you may use this code snippet that sums up all integers lower than 100 using parallel streams (it is multithread operation):

IntStream.range(0, 100).parallel()
        .forEach(i -> valueHolder.updateAndGet(x -> x.add(BigInteger.valueOf(i))));