问题
I have one customized list MyList that extends ArrayList, like this:
class MyList extends ArrayList<SomeParticularItem>{
[some methods...]
}
Since I have concurrent reads and writes to the list, I want to synchronize it:
MyList mylist = (MyList) Collections.synchronizedList(new MyList());
This seems to be fine, the .jar is build. Then, at runtime, I get:
java.util.Collections$SynchronizedRandomAccessList cannot be cast to MyList
Is there a better way (is there any way at all) to obtain a synchronized list of a list that inherits from some java.util.List?
回答1:
The easiest way to do it would be to extend Vector instead of ArrayList. You could also synchronize the methods of MyList yourself if you wanted to keep it as an ArrayList.
回答2:
Well why not make MyList synchronized, alternativly simply use the List interface List mylist = Collections.synchronizedList(new MyList());
Edit: You could of course let MyList extend Vector, since all of the Vectors methods are already synchronized you save some work.
来源:https://stackoverflow.com/questions/6598808/how-to-obtain-a-customized-synchronizedlist-in-java