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”,而中文文檔上沒有,也是由於剛開始看中文的,所以沒有注意到。最後比較兩個方法,文檔上也給出了很清楚的說明,自己卻沒注意到。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章