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!
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With