Java – is BigInteger thread secure?
I need to update the global BigInteger value through multiple threads – is BigInteger thread safe?
Solution
BigInteger objects are representative examples of immutable objects
For immutable objects, the state is fixed throughout the life cycle Because there is no option to change it, each "change" operation is equivalent to replacing a new object Therefore, after n threads on a specific reference execute a series of modifications in parallel, the result value is difficult to predict (some updates may be lost - unnoticed) The same story is integer class To overcome this limitation, the atomicinteger course was introduced into jdk5 Unfortunately, there is no "atomicbiginteger" class in the JDK Another solution is to wrap an object instance with an atomicreference – it acts as a proxy to synchronize and atomize all operations
I propose a compact solution that requires JDK 8:
final AtomicReference<BigInteger> valueHolder = new AtomicReference(BigInteger.ZERO);
Using this method, any method provided by BigInteger can be re expressed as a lambda expression, for example:
valueHolder.updateAndGet(x -> x.add(BigInteger.valueOf(10)));
To check that the solution is correct, you can use this code snippet to summarize all integers below 100 using a parallel stream (it is a multithreaded operation):
IntStream.range(0,100).parallel() .forEach(i -> valueHolder.updateAndGet(x -> x.add(BigInteger.valueOf(i))));