Is BigInteger Thread safe?

I have a requirement to update the global value of BigInteger across multiple threads - is BigInteger thread safe?

+6
source share
5 answers

BigInteger objects are a representative example of immutable objects .
Simply put:

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

For immutable objects, the state is fixed throughout the entire life cycle. Since there is no way to change it, therefore, each “change” operation is equivalent to replacing with a new object. Therefore, after a series of modifications performed in parallel by N threads on a specific link, the value of the result is difficult to predict (some updates may be lost - unnoticed).
The same story belongs to the class Integer . To overcome this limitation, AtomicInteger introduced the JDK5 class.
Unfortunately, there is no AtomicBigInteger class in the JDK. An alternative solution is to wrap an instance of an object using AtomicReference - which works as a proxy server that synchronizes all atomic operations.

I propose the following compact solution that requires JDK 8:

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

Using this approach, any method provided by BigInteger can be counted as a lambda expression, for example:

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

To verify the correctness of the solution, you can use this piece of code that sums all integers below 100 using parallel threads (this is a multi-threaded operation):

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

You cannot update BigInteger, read javadoc, its immutable integers with arbitrary precision. To update the BigInteger field, you will need to replace it with a new BigInteger, like this

 ... bigInteger = bigInteger.add(value); ... 

and this will require synchronization, otherwise two things can happen:

  • one thread changed the value, but other threads do not see the change

  • two or more threads are added at the same time, but some additions are lost.

+2
source

java.math.BigInteger is immutable and therefore safe to access by multiple threads.

Side note: Thread-safety is a term that refers to multiple threads accessing a piece of code (not just a variable).

+1
source

BigInteger is thread safe. But you want to update it, you should use this code:

 private BigInteger bigInteger = BigInteger.ONE; public void add(BigInteger plus) { bigInteger = bigInteger.add(plus); } 

therefore, synchronization is required.

0
source

BigInteger : Immutable integers with arbitrary precision.

Immutable objects : an object is considered immutable if its state cannot change after its creation . Maximum dependence on immutable objects is widely recognized as a sound strategy for creating simple, reliable code .

This means that BigInteger is thread safe.

0
source

All Articles