Is it safe to iterate over synchronized shells?

I decided to delve a bit into the source code and noticed that Collections.synchronizedList(List) implemented as follows:

 public static <T> List<T> synchronizedList(List<T> list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<T>(list) : new SynchronizedList<T>(list)); } 

where the SynchronizedList nested class:

 static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { private static final long serialVersionUID = -7754090372962971524L; final List<E> list; SynchronizedList(List<E> list) { super(list); this.list = list; } SynchronizedList(List<E> list, Object mutex) { super(list, mutex); this.list = list; } public boolean More ...equals(Object o) { synchronized(mutex) {return list.equals(o);} } //ommited public void add(int index, E element) { synchronized(mutex) {list.add(index, element);} } public E remove(int index) { synchronized(mutex) {return list.remove(index);} } //rest is ommited } 

As you can see, the class uses a private lock object to ensure thread safety. But the documentation allows us to iterate over it, using the lock on the objetct object returned by the factory method.

It is imperative that the user manually synchronizes the list when it repeats:

So, we use different locks to iterate and change the list ( add , remove , etc.).

Why is it considered safe?

+5
source share
1 answer

Collections#synchronizedList Method

 public static <T> List<T> synchronizedList(List<T> list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : new SynchronizedList<>(list)); } 

uses this single parameter constructor that you specified in your question. This constructor calls a super constructor that sets this as mutex . All methods are synchronized on mutex , this .

The documentation also indicates instance synchronization during iteration. This link is the same as this inside the method bodies.

All of these actions (if, if you do it right) must have the same lock.

+7
source

Source: https://habr.com/ru/post/1239762/


All Articles