Synchronization in Java – Vector vs ArrayList

Discussion DashboardCategory: JavaSynchronization in Java – Vector vs ArrayList
DHARMEDRA SAHU Staff asked 9 years ago
1 Answers
DHARMEDRA SAHU Staff answered 9 years ago

1
down vote
favorite
1

I am attempting to understand the difference between the Vector and ArrayList classes in terms of thread-safety. Vector is supposedly internally synchronized. Is it synchronized by each element, or as a whole? (I could imagine the case where multiple threads could access the vector at the same time, but multiple threads could not access the same element at the same time). If you look at the code below, getAo() is not equivalent to getV() because the synchronized keyword when used in a method signature synchronizes on the containing class object (an instance of VectorVsArrayList) to my knowledge. HOWEVER, is getAoSync() equivalent to getV()? By equivalent, I mean does the ao instance variable start behaving like a Vector object in terms of synchronization as long as all access to it goes through the getter method?

public class VectorVsArrayList {

private ArrayList ao = null;
private Vector v = null;

public ArrayList getAoSync(){
synchronized(ao){
return ao;
}
}

public synchronized ArrayList getAo() {
return ao;
}

public Vector getV() {
return v;
}

}