Can I use the standard Collections classes (as opposed to the concurrent ones) as long as I ensure the code makes no data changes on multiple threads. The code that I'm talking about is completely under my control, and I'm not mutating it after the initial (single-threaded) population phase.

I know that some classes such as DateFormat are not threadsafe because they store intermediate states as they are being used. Are the collections (ArrayList, Tree Map, etc.) safe though?

有帮助吗?

解决方案

Collections are generally safe for concurrent reading, assuming they are safely published. Apart from that, I'd also recommend the collections are wrapped with the unmodifiable wrappers (such as Collections.unmodifiableList) and that the elements in them are immutable (but you probably already knew this).

其他提示

Yes. In the Java API docs, each non-threadsafe collection has a warning similar to this one in TreeMap:

Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.)

Emphasis mine. As long as there are zero structural modifications, you should be just fine without external synchronization.

The collections are safe for read and your use case (initialize once then use) is fine.

The thing to be careful of if you try and extend this is that even if only one thread is modifying collections or the objects inside collections then that can have consequences for reader threads.

No, you must check two kinds:

  • Multiple Threads (as you wrote).
  • Same Thread in a current, open Iterration.

If you check this two, you are fine to use standard collections.

Regards.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top