How to obtain a customized synchronizedList in java?

廉价感情. 提交于 2019-12-11 08:04:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!