Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing an int or an integer object between multiple threads in Java

I have a multithreaded program that includes data structures like ConcurrentHashMap and ConcurrentLinkedList, however I also need every thread to access a shared integer value. The threads themselves are custom thread classes I've made that extend class Thread. My two concerns here are:

  • How can I make each thread see the same integer value? I don't think a primitive int would work as it would not be "passed by reference" (or rather passed by value of the object pointer). The integer needs to be mutable and any changes to one integer by a thread needs to be seen by all the other threads. Would using an Integer Object fix this, what about AtomicInteger?

  • What should I use to preserve thread safety? Each thread will check the integer everytime a loop in them runs but it will change the integer when a thread has finished it's task and is about to return.

Thanks in advance!

like image 625
Kode47 Avatar asked May 12 '26 16:05

Kode47


2 Answers

You should use an AtomicInteger.

I would however consider AtomicInteger as a fairly low level primitive. I would question the design. Have you considered using ExecutorService, Callable, Futures, Semaphore, CountDownLatch, the Fork/Join framework or other classes from the high level java.util.concurrent API?

like image 190
aioobe Avatar answered May 15 '26 06:05

aioobe


You can use AtomicInteger . It supports many atomic operation. For e.g. addAndGet, decrementAndGet, etc. AtomicInteger does extend Number , so you can pass it to methods that operate on numerically based classes.

like image 30
sol4me Avatar answered May 15 '26 06:05

sol4me



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!