• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

vector: synchronized data or synchronized method

 
Yan Zhou
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
mike acre
Ranch Hand
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic