Forums Register Login

vector: synchronized data or synchronized method

+Pie Number of slices to send: Send
One SCJD textbook says:

Vector provides synchronized methods to access data, but vector itself is not synchronized data, and there is a big difference.

I do not see how they are different from a programmer 's viewpoint: since all methods are synchronized, the internal data integrity of a vector is always maintained.

What did I miss?
Thanks.
Yan
+Pie Number of slices to send: Send
Vector as an object is thread-safe (synched methods) same goes for obtaining a List like so:

Collections.synchronizedList(new ArrayList());

[Incidentally don't use Vectors if you can help it, they are more or less deprecated]

But all this means is that multiple threads will not corrupt the data within the Collection. ie when a thread puts something at index 12 then that is where it goes. This guarantee does not hold for a plain List.
The upshot is that there is a big performance gain in regular Lists when concurrency isn't an issue.

However you must still ensure that the code that uses a thread-safe Collection is thread-safe itself. It doesn't have magic powers!

if(myList.contains(myObj)) {

myList.remove(myObj);
}

does that look thread-safe, whatever the flavour of the List?
Space seems cool in the movies, but once you get out there, it is super boring. Now for a fascinating tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 423 times.
Similar Threads
vector or arrayList
synchronized classes?
Vector vs ArrayList
vector: synchronized data and synchronized method
A Vector class is a Threadsafe
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 09:04:02.