Vector's Synchronization Mechanism
What you'll learn: How Vector achieves thread safety through method-level synchronization and the performance cost it imposes.
The Synchronized Approach
Every public method in Vector is marked with the synchronized keyword. This means when one thread calls add(), get(), remove(), or any other Vector method, it must first acquire the monitor lock on that Vector object. All other threads trying to access any synchronized method on that same Vector must wait until the lock is released.
What This Means in Practice
Think of Vector like a single-occupancy restroom with one key. Even if 10 people want to use it, only one person can be inside at a time—everyone else waits in line. Similarly, even if you have 10 threads and they're calling different Vector methods, they all compete for the same lock and execute one at a time.
Vector<String> names = new Vector<>();
// This method is synchronized
names.add("Alice"); // Thread must acquire lock
// So is this one
String first = names.get(0); // Same lock required
// And this
int count = names.size(); // Still the same lock
The Performance Overhead
Synchronization isn't free:
- Lock acquisition/release adds overhead to every single method call
- Thread contention causes threads to block and wait unnecessarily
- No concurrent reads even though multiple threads could safely read simultaneously
This is why ArrayList replaced Vector for most use cases—you only pay for synchronization when you actually need it.
Key Takeaway:
Vector synchronizes every method call with a single object lock, ensuring thread safety but creating performance overhead even when concurrent access isn't needed or when operations span multiple method calls.