2

Sorry if this was asked before, but I could not find my exact scenario.

Currently I have a background thread that adds an element to a list and removes the old data every few minutes. Theoretically there can be at most 2 items in the list at a time and the items are immutable. I also have multiple threads that will grab the first element in the list whenever they need it. In this scenario, is it necessary to explicitly serialized operations on the list? My assumption that since I am just grabbing references to the elements, if the background thread deletes elements from the list, that should not matter since the thread already grabs a copy of the reference before the deletion. There is probably a better way to do this. Thanks in advanced.

4
  • Would it matter if multiple threads grabbed the same "first element"? Commented Apr 10, 2012 at 22:28
  • If thread A changes the list, and another thread B reads the list after that change, you have no guarantee that B will see the change made by A without synchronization, even if both threads hold the reference to the list. Commented Apr 10, 2012 at 22:45
  • Since the elements are immutable, I don't think it matters Commented Apr 10, 2012 at 22:48
  • @assylias I forgot to mention that I don't care if a thread grabs stale data as long as it grabs something. My goal is for the server never to crash from this simple operation with the emphasis on performance =P Commented Apr 10, 2012 at 22:50

1 Answer 1

1

Yes, synchronization is still needed here, because adding and removing are not atomic operations. If one thread calls add(0, new Object()) at the same time another calls remove(0), the result is undefined; for example, the remove() might end up having no effect.

Depending on your usage, you might be able to use a non-blocking list class like ConcurrentLinkedQueue. However, given that you are pushing one change every few minutes, I doubt you are gaining much in performance by avoiding synchronization.

Sign up to request clarification or add additional context in comments.

2 Comments

That looks like something I need. Thanks! However, there it is only possible for 1 thread to modify the list in my scenario. Does the situation still apply for me?
As @Russell said, updating the list is not atomic unless you synchronize. You need synchronization whenever there is more than one thread, and at least one thread changes the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.