Search code examples
javamultithreadingthread-safetyatomic

How to check if an ArrayList contains an element atomically?


Let's say, We're trying to add several elements into an ArrayList. At the same time, the same list is being searched for list.contains(givenElement).

Then, how do we achieve thread-safety without locking the whole list object? In other words, how can multiple threads access this list and perform operations atomically? I would like to know how to achieve this using AtomicReference.

I can create an AtomicReference variable with the list loaded in it. But, then how do I do contains() operation atomically without doing compareAndSet() on whole list ?

Note that I'm looking for solutions other than using thread-safe collections.


Solution

  • If the list itself doesn't change then you should not be looking at AtomicReference.

    It looks like you need ReadWriteLock, allowing multiple threads to check the list at once while locking during changes to the list.

    To check if it is in the list you need Lock readLock() and to change it Lock writeLock().

    There are many examples for this kind of usage.

    After comment from OP: Changes not just compare can be made.

    Get the readLock, see if it is contained in the list, then get the writeLock if you have to add it to the list. You only acquire the writeLock if a change is needed.