Rohan Jhunjhunwala Rohan Jhunjhunwala - 5 months ago 8
Java Question

AtomicReference<ArrayList> difficulties and alternatives

So in various programs that I have been writing for fun, I have come across concurrent modification exceptions.

In my naive attempt to solve this problem I used an Atomicinstead of some sort of concurrent collection. I am somewhat familiar with why this is casing errors. Essentially the individual elements of the ArrayList are not synchronized and can be modified at whim by different threads.



Could someone summarize for me

  • What errors occur when i try to make an atomic reference to a collection on a collection

  • What is a legitimate use case for an atomic reference to an Array or list

  • What are some better alternatives for storing instances for a game which can be used by multiple threads




  • Answer

    Using AtomicReference to store an object such as a collection is not enough to make it thread safe. Indeed if the object that you put in the AtomicReference is not thread safe like an ArrayList for example, using it would still be unsafe if we have multiple threads trying to modify its state concurrently. So the good approach is still to put into your AtomicReference an immutable object such that its state cannot be modified by multiple threads anymore. In case of a collection you can for example use the methods of type Collections.unmodifiable* such as Collections.unmodifiableList(List) for the lists, in order to put into the AtomicReference the immutable version of your collection.

    If you need thread safe collections, you should have a look to the classes in the package java.util.concurrent, you will find Collections natively thread safe. For example, if you mostly read and rarely modify your List, you can use the thread safe and efficient list CopyOnWriteArrayList.