SelectionKeys在删除时报java.lang.UnsupportedOperationException错

昨天晚上在写java nio通讯的时候,报了下面的异常,到网上找了很长时间,终于解决了。
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection$1.remove(Collections.java:1012)
出错的原因是写了如下代码:
Selector selector = Selector.open();
Iterator<SelectionKey> it = selector.keys().iterator();
while(it.hasNext()) {
SelectionKey key = it.next();
it.remove();

报错在最后一行产生,产生这个错误也很让人郁闷,调试了大半天也没结果,从源码也找不到原因。
java官方资料([url]http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=c7a0b0ec57e0dffffffffd21d2237d896878?bug_id=5098171[/url])上给出一个解释,说这个不是一个bug,并给出了示例代码,也指出了出错的地方和解决方案。只需要把selector.keys()换成selector.selectedKeys()就可以了。
现在感觉看英文文档有很必要,因为英文文档已经给出很明确的提示:“Keys are added to the selected-key set by selection operations. A key may be removed directly from the selected-key set by invoking the set's remove method or by invoking the remove method of an iterator obtained from the set. Keys are never removed from the selected-key set in any other way; they are not, in particular, removed as a side effect of selection operations. Keys may not be added directly to the selected-key set.”。中间反复出现了“selected-key”,而中文文档上没有,也是由于刚开始看中文的,所以没有注意到。最后比较两个方法,文档上也给出了很清楚的说明,自己却没注意到。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章