wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes vetor thread safe? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "vetor thread safe?" Watch "vetor thread safe?" New topic
Author

vetor thread safe?

Robert Kennedy
Ranch Hand

Joined: Jun 27, 2008
Posts: 63
Hello,

If I use a vector to store some objects much I synchronize access or is it thread safe?

Thanks
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41137
    
  45
It is thread-safe.


Ping & DNS - my free Android networking tools app
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2999
    
    9
It is, technically, in the sense that each method individually is thread-safe. However it's difficult to accomplish anything useful with this class without some additional synchronization. For example when iterating, you need to synchronize, as shown here. Yes, that discussion is for Collections.synchronizedList(), but Vector works the same way. The basic problem is that while each individual method call is synchronized, nothing prevents other threads from inserting other method calls in between two calls that really need to go together. If you've just made a call to iterator.hasNext() and it returned true, can you safely call iterator.next()? Not without extra synchronization - because how do you know that some other thread didn't remove() or clear() the next item, immediately after you called hasNext()? In general, you don't. There are other examples where Vector and synchronizedList() usage require additional synchronization, but iteration is the most common.

My own opinion is that the synchronization in Vector and Collections.synchronizedList() is close to useless, and dangerously misleading. You're usually better off synchronizing on the list externally, using synchronized blocks. Or writing the code in a way that no synchronization is required at all.
Robert Kennedy
Ranch Hand

Joined: Jun 27, 2008
Posts: 63
Thank you very much for your detailed explanation. I will use locks.
 
Consider Paul's rocket mass heater.
 
subject: vetor thread safe?
 
Similar Threads
How can we count the number of objects created per class using Java1.5 API?
BeanUtils.copyProperties
can someone give a good example for ThreadSafe servlet
threadsafe objects
EJB 3.0: EntityManager Injection in SLSB