I needs to develop a threading based application. The application will perform complex real time calculations, which includes about 80% read operations and about 20% write operations.
The application should have the ability to:
Efficiently use Memory resource
Perform fast operations
Maintain insertion order of elements and
Run in thread-safe mode
which of the following java collection will you prefer?
Justify your answer in each case.
Steve Luke wrote:Neither. My first option would be CopyOnWriteArrayList because thread safe access where reads out number writes is what it is optimized for
Well, maybe. According to the docs, it's optimized for cases where reads vastly outnumber writes. "Vastly" is not defined, but I suspect 20% writes 80% reads might not be a big enough difference to justify CopyOnWriteArrayList.
But, as you say:
Steve Luke wrote:There are cases where it is not appropriate so I would measure and if I saw a problem them I might search for a different implementation that better matches the use case.
Yes, definitely measure.
For an alternative, if needed, I would definitely prefer using ArrayList (or possibly LinkedList or ArrayDeque or other implementation) over Vector. Add synchronization explicitly where you need it. Do not rely on the built-in synchronization of Vector; it is usually too low-level to be truly useful, and misleads many people into thinking they are thread-safe when they are not. You almost always need additional synchronization anyway, so making all your synchronization explicit in your code seems clearer and safer, to me.
Just a simple example to follow up on Mike's statement about how the unwary programmer can be misled by the "thread-safe" label:
The beginner might think that "thread safety" of the list would make that acceptable code to ensure that the list contained only one instance of the value. But it isn't. You need that additional synchronization which Mike mentioned.
Given the choices, limited to either Vector or ArrayList, I'd definitely go with ArrayList. Vector is widely considered obsolete, though it is not officially flagged as deprecated. Also the same thread-safety promises made by Vector can trivially be applied to ArrayList simply by wrapping it via Collections#synchronizedList(). The most compelling reason, though, has already been stated by Mike and Paul, which is that the thread-safety guarantees made by Vector are often insufficient or cause too much contention, or both. So definitely ArrayList.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.