Please refer to the following java source code :
static class SynchronizedList<E>
extends SynchronizedCollection<E>
implements List<E> {
final List<E> list;
public boolean equals(Object o) {
synchronized (mutex) {return list.equals(o);}
}
public int hashCode() {
synchronized (mutex) {return list.hashCode();}
}
public ListIterator<E> listIterator() {
return list.listIterator(); //Must be manually synched by user
}
My question is why is the listIterator() not guarded by the mutex as with hashcode() and equals() method ? Why did they design it so that it requires external synchronization by the user ?
The main usage of ListIterator is not in obtaining it , but actually iterating it over for visiting individual elements in the list. This is a stateful operation and is entirely done by the client and not by the class
SynchronizedList. On the other hand , the methodsequals()andhashCode()are entirely computed within theSynchronizedListand do not require client to do much expect to take the returned values. Synchronizing the method to obtain the iterator is not much helpful as user1252434 pointed out.ListIterator is a classic example of using client-side locking as a strategy to ensure synchronization when the original class cannot provide for this.