Re: Vector (was Re: Change character in string)
Andreas Leitgeb wrote:
Bent C Dalager <bcd@pvv.ntnu.no> wrote:
Either way of doing it is wrong: in one case you end up deadlocking
and in the other you're not synchronizing on all the data that you
need. And neither of these flaws is obvious to the user, or even
documented in any way that I know of.
So that's now 100 penalty points this time against sync'd ArrayList?
The world just refuses to be simple.
It's not a penalty against either one. Neither synched class can claim to be
thread-safe.
As Goetz's /Java Concurrency in Practice/ and other sources point out,
whenever one deals with multiple objects cooperating to provide shared state
or multiple methods interacting with shared state, it is not sufficient to
synchronize on only one object or method at a time.
Examples where this pertains include the broken double-checked locking idiom,
check-and-set scenarios, and the thing that messed up 'Vector#equals()',
acquisition of multiple locks from different threads in a different order from
each other.
Bent's example of deadlock rested on a deliberate violation of proper
concurrency practice. It is the sort of violation that can readily happen
unintentionally in a larger context.
As to the great "Vector vs. ArrayList" cage match, the decision rests on which
one is easier to control. For applications that need a totally thread-safe
'equals()' comparison of lists, one cannot rely on the internal
synchronization of a synched 'List', neither version. One must use explicit
synchronization, ergo probably an unsynchronized 'List' implementation like
'ArrayList' (without a 'synchronizedList()' wrapper) under a caller's lock.
In other words, both 'Vector' and 'synchronizedList()' lose in favor of
correct coding with careful thought.
Yet another reason to eschew 'Vector' - the myth that it's thread-safe leads
one astray, and the fix leads back to a "real" collections-framework 'List'
anyway.
--
Lew