Alex Rivera | Logout

Thread-safe iteration over a collection

Asked 2010-12-23T10:00:36.437
19

We all know when using Collections.synchronizedXXX (e.g. synchronizedSet()) we get a synchronized "view" of the underlying collection.

However, the document of these wrapper generation methods states that we have to explicitly synchronize on the collection when iterating of the collections using an iterator.

Which option do you choose to solve this problem?

I can only see the following approaches:

  1. Do it as the documentation states: synchronize on the collection
  2. Clone the collection before calling iterator()
  3. Use a collection which iterator is thread-safe (I am only aware of CopyOnWriteArrayList/Set)

And as a bonus question: when using a synchronized view - is the use of foreach/Iterable thread-safe?

Edit
Report

1 Answer

1

I suggest dropping Collections.synchronizedXXX and handle all locking uniformly in the client code. The basic collections don't support the sort of compound operations useful in threaded code, and even if you use java.util.concurrent.* the code is more difficult. I suggest keeping as much code as possible thread-agnostic. Keep difficult and error-prone thread-safe (if we are very lucky) code to a minimum.

answered 2010-12-23T13:06:59.033

Your Answer