Thread-safety and Vector a thread-safe
Thread-safety is a concept in concurrent programming where a piece of code or a data structure is designed to function correctly during simultaneous execution by multiple threads. A thread-safe class or method ensures that its behavior remains consistent and predictable, even when accessed by multiple threads at the same time, without introducing race conditions or data inconsistencies.

Table of Contents
Key Points of Thread-Safety
- Consistency: Operations performed by multiple threads do not leave shared data in an inconsistent state.
- Atomicity: Operations are completed entirely without interference from other threads.
- Isolation: Each thread’s operations do not affect the operations of other threads.
Is Vector a Thread-Safe Class?
Yes, Vector is a thread-safe class in Java. It is part of the Java Collections Framework and is a synchronized version of ArrayList. All the methods of Vector are synchronized, which ensures that only one thread can execute a method at a time, thereby making it thread-safe.
However, using Vector might lead to performance issues in highly concurrent environments due to the overhead of synchronization. In such cases, alternatives like Collections.synchronizedList() or concurrent collections from java.util.concurrent package (e.g., CopyOnWriteArrayList) are preferred.
Using Vector
Below is an example demonstrating the thread-safe nature of Vector.
java
import java.util.Vector;
class VectorExample extends Thread {
private Vector<Integer> vector;
public VectorExample(Vector<Integer> vector) {
this.vector = vector;
}
public void run() {
for (int i = 0; i < 5; i++) {
vector.add(i);
System.out.println(Thread.currentThread().getName() + " added: " + i);
try {
Thread.sleep(50); // Simulate some work
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Vector<Integer> vector = new Vector<>();
Thread t1 = new VectorExample(vector);
Thread t2 = new VectorExample(vector);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Vector content: " + vector);
}
}
Explanation
Thread Definition
- VectorExample class extends Thread and has a Vector object.
- The run() method adds integers to the Vector and prints a message for each addition.
Main Method
- A Vector object is created.
- Two VectorExample threads are created and started.
- The main thread waits for both threads to finish using join().
Thread-Safety
- Since Vector methods are synchronized, the addition of elements is thread-safe. Even though multiple threads are adding elements concurrently, the Vector maintains a consistent state.