I have a list of strings shared between a number of threads. Each thread has to:
- access the list (for example via a getter method);
- get the size of the list;
- choose a random number n between zero and list.size();
- extract the element at offset n from the list;
- delete the extracted element from the list;
- "save" the list back so that other threads view always the updated list
Since there is a concurrent access to a mutable shared object (the list), I need to code in a thread-safe way. Each thread has to diminish the list size by one and for this reason every other thread access must see a shorter list. My aim is to avoid a thread can see the same list seen by another thread, because in this way there is the possibility that the same element could be extracted twice.
Which is the best way to accomplish this? I was thinking about CopyOnWriteArrayList but I'm not sure it behaves like I need.
Thank you