2

I have a list of strings shared between a number of threads. Each thread has to:

  1. access the list (for example via a getter method);
  2. get the size of the list;
  3. choose a random number n between zero and list.size();
  4. extract the element at offset n from the list;
  5. delete the extracted element from the list;
  6. "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

2 Answers 2

7

The problem is that operations 1 to 6 need to be atomic and using a CopyOnWriteArrayList won't solve that.

One solution is to simply synchronize the whole operation:

private final List<String> list = new ArrayList<String> (); public String getNextItem() { synchronized(list) { //get the string adn remove it from the list } return next; } 

Alternatively, you could review your algorithm and do something like:

  • create the list
  • shuffle it (to introduce randomness)
  • populate a BlockingQueue with that list (for example a LinkedBlockingQueue)
  • have your threads take items from the queue (thread safe atomic operation => no additional synchronization required)
Sign up to request clarification or add additional context in comments.

2 Comments

like your alternative approach :)
the BlockingQueue approach seems simpler, because then I would have no need to save back an updated version of the list. Thank you
0

I don't see any reason why you cannot put the above sequence of logic in a synchronize block, or using semaphore/mutex for exclusive access to list during the above sequence of logic.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.