Replace a class inheriting from ArrayList<A>
with an interface and a class containing the list:
interface ListA extends List<A> {
// Put additional methods here
}
class ListAImpl implements ListA {
private List<A> content;
public ListAImpl(List<A> content) {
this.content = content;
}
// Use delegation for all methods of the List<A> interface, calling through
// to the content list.
}
Now the synchronization of your ListA
object depends on what you pass to its constructor: pass a "plain" ArrayList<A>
to have a non-synchronized ListA
, or pass a synchronized one to have a synchronized ListA
.
Now your code snippet when you make a synchronized ListA
from a non-synchronized one like this:
ListA a = new ListAImpl(new ArrayList<A>());
ListA sync = new ListAImpl(Collections.synchronizedList(a));