ArrayList的ConcurrentModificationException

package list;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo2 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("hello");
list.add("world");
list.add("java");
list.add("world");
list.add("java");
list.add("world");
list.add("world");
list.add("world");
list.add("world");
list.add("java");
list.add("world");
Iterator it = list.iterator();
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i).equals(list.get(j))) {
list.remove(j);
j--;
}
}
}
while (it.hasNext()) {
System.out.println((String)it.next());
}
}
}
运行时报错:Exception in thread "main" java.util.ConcurrentModificationException,请问怎么解决/

1个回答

你把 Iterator it = list.iterator(); 这行移到for() 循环下面就可以了

放上面得到的是就list 的 Iterator

rke_poke
rke_poke 回复yanmengdewo: 知道了,谢谢!
2 年多之前 回复
yanmengdewo
yanmengdewo 回复rke_poke: 放上面得到的是旧list 的 Iterator 执行for()循环后。list 中的内容发生了变化,用老的 Iterator去遍历是会出错的
2 年多之前 回复
rke_poke
rke_poke 谢谢,这样 确实解决问题了,可以具体解释一下原理吗?
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
ConcurrentModificationException
[code=java]HashMap activeUsers = core.getUsers();rn Iterator> it = activeUsers.entrySet().iterator();rn while(it.hasNext())rn Map.Entry entry = (Map.Entry) it.next();rn log.info(entry.getKey()+" "+entry.getValue());[/code]rn这个在it.next的时候报rnjava.util.ConcurrentModificationExceptionrn at java.util.HashMap$HashIterator.nextEntry(Unknown Source)rn at java.util.HashMap$EntryIterator.next(Unknown Source)rn at java.util.HashMap$EntryIterator.next(Unknown Source)rn at com.dgF.sms.core.thread.DealSubmitSMSThread.run(DealSubmitSMSThread.java:38)
ConcurrentModificationException 错误
我在网上搜索过了 遍历过程中增删list造成的 但是我试过了将变量保存起来,遍历完统一删除 还是会报错 逻辑没有问题 rnrnrnrn我的问题是这样的:rn我写了一个飞行射击游戏,有时候飞机会以一定的组合顺序出现,我把它叫做敌阵 ,我写了一个基于定时器的基类,敌阵类继承自这个类,在类中的 timertask中按一定顺序生成敌机加入链表中 , 然后在绘制每一帧的时候检测碰撞并且把碰撞的对象在链表中删掉,一般同时有好几个定时器存在,timertask中我也加入同步变量 rnrn=new TimerTask() rn public void run() rn if(getSynflag()==false) rn return;rn rnrn每次遍历的时候 用 setSynflag (false) 将 定时器锁住 使它不会增加list中的值 rn遍历中的值不会直接删掉 用一个list记录 遍历完毕统一删除rnrnrnrnrnrn但还是出现这个错误 list在遍历的时候明明已经不能变化了 rnrnrn使用了安全线程的CopyOnWriteArrayList也没有用 rnrn项目下载地址 rnhttp://pan.baidu.com/s/1pJBcpmzrnrn这是我自己兴起写的一个程序 希望能有人帮我看看调试一下 谢谢了 rnrnrnrnrnrn
ConcurrentModificationException的例子
[code=java]public class MapIterator rnrn public static void main(String[] args) rnrn Map map = new HashMap();rn map.put("a", "tangsc");rn map.put("b", "songyuanyuan");rnrn System.out.println("HashMap before iterator: " + map);rn Iterator it1 = map.keySet().iterator();rn while (it1.hasNext()) rn String key = it1.next();rn if (key.equals("a")) rn map.put("c", "name");rn rn rn System.out.println("HashMap after iterator: " + map);rnrnrn rnrnrn[/code]rnrn大家看看,为什么我这段代码不会引起ConcurrentModificationException,好奇怪
java语言基础(66)——集合框架(arrayList ConcurrentModificationException 并发修改异常的解决方案)
问题重现: package ArrayListDemo; import java.util.ArrayList; import java.util.Iterator; public class ArrayListDemo { /** * @param args */ public static void main(String[] args) { ArrayList
ConcurrentModificationException问题?
[code]rnimport java.util.*;rnrnpublic class TryIteratorRemove rn public static void main(String [] args)rn Collection myCollection = new ArrayList(10);rn rn myCollection.add("123");rn myCollection.add("456");rn myCollection.add("789");rn rn int i=0;rn rn for(Iterator it = myCollection.iterator();it.hasNext();) rn String myObject = (String)it.next();rn System.out.println(myObject);rn rn i++;rnrn if(i==1)rn //myCollection.remove(myObject);rn it.remove();rn rn rnrn System.out.println("After remove,the size of myCollection is: " +rn myCollection.size()+" \n and its content is: ");rnrn for(String s : myCollection)rn System.out.println(s);rn rn rnrn[/code]rnrn 对于上面这段程序,为什么用'myCollection.remove(myObject);'时会报'ConcurrentModificationException'异常?而用'it.remove();'时没事呢?rnrn 我想从Java的源代码上找解释,可不知道从哪个类入手,把能想到的类都看了看,也没有解释通,请高手帮我看看。rn 谢谢!!rnrn后来从书上看到以下解释:rn "if one thread changes a collection while another rnthread is traversing it through with an iterator the iterator.hasNext() or iterator.next() call will throw rnConcurrentModificationException. Even the synchronized collection wrapper classes SynchronizedMap and rnSynchronizedList are only conditionally thread-safe, which means all individual operations are thread-safe but compound rnoperations where flow of control depends on the results of previous operations may be subject to threading issues."rn 不过我有以下疑问:rn 1,上面程序出错是由于线程问题吗?上面说到'当一个线程用iterator遍历collection时,另一个线程修改colleciton,iterator.hasNext()或iterator.next()就会抛出ConcurrentModificationException异常'。我想知道在上面我写的那段程序中是main线程修改这个collection吗?那对collection进行遍历的线程又是哪个呢?是Iterator自己又开了一个线程?rn 2,有没有例子演示下'all individual operations are thread-safe but compound rnoperations where flow of control depends on the results of previous operations may be subject to threading issues.'这段说的是什么?这个individual operations指的会是什么?
ArrayList删除倒数第二个元素不报ConcurrentModificationException原因-----阿里开发手册
详解ArrayList迭代删除,迭代ArrayList时删除ArrayList的倒数第二个元素是不会报ConcurrentModificationException异常
【拾遗补缺】java ArrayList的不当使用导致的ConcurrentModificationException问题
今天组内的一个同学碰到一个并发问题,帮忙看了下。是个比较小的点,但由于之前没碰到过所以也没特意了解过这块,今天既然看了就沉淀下来。 原始问题是看到日志里有一些零星的异常,如下如所示 根据堆栈信息,可以很快定位到对应的应用代码,同时根据异常的描述,可以初步定为是并发访问ArrayList造成的。 相关应用代码如下(也就是堆栈第三行的Com...
android异常 ConcurrentModificationException()
要进行的操作是,遍历map.判断key值是否存在。如果存在,,则this key对应的valuez增加一个list,否则的话,就重新再添加一组键值对,nnnprivate Map> modleLists() n List lists = new ArrayList();n Map> maps = null;n for (int i = 0; i < carInfoLists.size(); i++) n if (maps == null) n maps = new HashMap>();n lists.add((carInfoLists.get(i)));n maps.put(carInfoLists.get(i).getModleName(), lists);n else n Iterator>> it = maps.entrySet().iterator();n while (it.hasNext()) n Entry> next = it.next();n String key = next.getKey();n if (carInfoLists.get(i).getModleName().equals(key)) n CarModle carModle = carInfoLists.get(i);n maps.get(key).add(carModle);n else n lists.clear();n lists.add(carInfoLists.get(i));n maps.put(carInfoLists.get(i).getModleName(), lists);n nn
android异常 ConcurrentModificationException();
在对map集合遍历key,并且判断key值是否存在,然后添加对应的value时,put了两次key之后,到第三次再判断时候抛出异常 throw new ConcurrentModificationException();,,nn这是主要代码nnprivate Map> modleLists() n List lists = new ArrayList();n Map> maps = null;n for (int i = 0; i < carInfoLists.size(); i++) n if (maps == null) n maps = new HashMap>();n lists.add((carInfoLists.get(i)));n maps.put(carInfoLists.get(i).getModleName(), lists);n else n for (String key : maps.keySet()) n if (key.contains(carInfoLists.get(i).getModleName())) n CarModle carModle = carInfoLists.get(i);n maps.get(key).add(carModle);n break;n else n lists.clear();n lists.add(carInfoLists.get(i));n maps.put(carInfoLists.get(i).getModleName(), lists);n n nn n
如何解决ConcurrentModificationException问题
在当前的Java面试和后台开发中,多线程与线程池技术越来越重要。毫不夸张的说,如何你想进入任何一家好的网络公司并能够长足发展,多线程与线程池技术是必须要掌握的技能!
还是ConcurrentModificationException问题
想用Iterator遍历一个LinkedList,在使用完其中的一个元素后,就将它删除rnimport java.util.*;rnrnpublic class Controllerrn private List eventList = new LinkedList();rn public void addEvent(Event c)eventList.add(c);rn public void run()rn List subList = new LinkedList();rn Iterator it = eventList.iterator();rn while(it.hasNext())rn Event x =it.next();rn if(x.ready())rn System.out.println(x);rn x.action();rn subList.add(x);rn rn rn eventList.removeAll(subList);rn rnrn这里的subList和eventList指向的不是同一个引用啊,也没在遍历的时候删除元素,为什么还是抛出了ConcurrentModificationException???
购物车问题:ConcurrentModificationException
我在设计网上书店时,如果将购物车中的某本书删除,或者清空购物车时,因为改变了购物车集合中的内容,会产生ConcurrentModificationException,请问如何解决呢?谢谢各位!
集合的遍历(多线程)及ConcurrentModificationException
为了保证线程安全,在迭代器迭代的过程中,线程是不能对集合本身进行操作(修改,删除,增加)的,否则会抛ConcurrentModificationException的异常。 public class TestConcurrent { public static void main(String[] args) { Collection num = new ArrayList(); num
ConcurrentModificationException如何解决
public static void main(String[] args) rn List personDisList = new ArrayList();rn Person person1 = new Person();rn Person person2 = new Person();rn person1.setId("1");rn person2.setId("2");rn personDisList.add(person1);rn personDisList.add(person2);rn rn List personList = new ArrayList();rn for (int i=0; i
ThreadLocal 多线程下报 ConcurrentModificationException
代码在公司内网,没有办法发出来。rn我把程序流程的伪代码发出来,请大佬帮忙解决问题。谢谢。rn rn```rn//信号量控制并发rnprivate Semaphore semaphore=new Semaphore(4);rnrnpublic void run()rn for(int i=0;i<3600;i++)rn 获取一个信号量rn singleJob();rn rnrn rn@Asyncrnpublic void singleJob()rn tryrn User user=new User ();rn //将User设置入 ThreadLocalrn method1();rn method2();rn method3();rn //取出User存入数据库。rn cache(Exception e)rn finallyrn //释放信号量rn //清空ThreadLocal中设置的 Userrn rnrn```rn声明:@Async注解生效了 是多线程。rnrn我在singleJob里创建了一个User对象(举例而已),放进了ThreadLocal,在下面的三个方法中都从ThreadLocal中先取出user,然后设置user的一个属性再放入 ThreadLocal中。rn在finally块中从线程中移除。rnrn程序每次执行都至少会抛出1-2次ConcurrentModificationException。
关于ConcurrentModificationException的产生原因和解决方法
这几天一直在写一个游戏,里面会用到很多集合。而且需要在JPanel上面把这些对象集合一个一个用画笔画出来,就涉及到遍历集合的问题(大部分使用的foreach遍历)。但是游戏运行过程中会报错,就是(ConcurrentModificationException)并发修改异常这个错误。下面我举个例子,你就明白了。 public class Demo2 { public static void ma
关于ConcurrentModificationException异常原因及注意事项
嗨,大家好!最近在工作中遇到了一个棘手的问题(如题),特此在这里跟大家分享一下,第一次发博客,不足之处大家见谅! 异常出现原因:ConcurrentModificationException这个异常继承自RuntimeException,见名知意,这个异常一般是在Collection 上进行迭代,检测到对象的并发修改,但不允许这种修改时,抛出此异常,废话不多说,直接上干货,下面是几种出现这种异常的情
ConcurrentModificationException求各位大哥帮忙!
错误信息:rnrnorg.eclipse.swt.SWTException: Failed to execute runnable (java.util.ConcurrentModificationException)rn at org.eclipse.swt.SWT.error(SWT.java:4282)rn at org.eclipse.swt.SWT.error(SWT.java:4197)rn at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:138)rn at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4140)rn at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)rn at org.betguide.autobet.view.Main.open(Main.java:197)rn at org.betguide.autobet.view.Main.main(Main.java:111)rnCaused by: java.util.ConcurrentModificationExceptionrn at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)rn at java.util.LinkedList$ListItr.next(Unknown Source)rn at org.betguide.autobet.view.Main$2.run(Main.java:237)rn at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)rn at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)rn ... 4 morernrnrnpublic void open() rnrn IDBMonitor monitor = new H2Monitor();rn monitor.startup();rn display = Display.getDefault();rn createContents(monitor);rn LogManager.printConsole("初始化界面", "主界面", "登录");rnrn /**/rn User user = new User();rn user.setName("cwl");rn user.setPassword("cwl");rn UserSession.getInstance().setGlobalUser(user);rn UserSession.getInstance().setChannel(rn SocketClient.getInstance().connect());rn // 建立三主工作任务rn CheckProcessingJob job = new CheckProcessingJob();rn BetProcessingJob betJob = new BetProcessingJob();rn SureBetManagerJob surebetJob = new SureBetManagerJob();rn // 建立主线程 管理各自工作任务rn BetWorkerThread betworker2 = new BetWorkerThread("checkjob", job);rn BetWorkerThread betworker1 = new BetWorkerThread("betjob", betJob);rn BetWorkerThread betworker3 = new BetWorkerThread("surebetjob",rn surebetJob);rn betworker2.start();rn betworker1.start();rn betworker3.start();rn taskList = Collectionsrn .synchronizedList(new LinkedList());rn taskList.addAll(SureBetManagerJob.getTask());rn Thread t = new Thread(new Runnable() rn public void run() rn try rn while (true) rn List list = SureBetManagerJobrn .getTask();rnrn if (!compare(taskList, list)) rn rn changeSurebetView();rn taskList.removeAll(taskList);rn taskList.addAll(list);rnrn rn try rn Thread.sleep(1000);rn catch (InterruptedException e) rn // TODO Auto-generated catch blockrn e.printStackTrace();rn rn rn catch (Exception e) rn // TODO Auto-generated catch blockrn e.printStackTrace();rn rnrn rnrn );rn t.start();rn /**/rn shell.open();rn shell.layout();rn while (!shell.isDisposed()) rn if (!display.readAndDispatch()) //报错提示在这一行rn display.sleep();rn rn
ArrayList[]与ArrayList()的问题
我一直想不通这两者有什么联系和区别,到底ArrayList[]是动态数组还是ArrayList()是??rn我想从一个数组里提取一个数,并且数组里的元素同时去掉这个数··用前者的话不能删减,用后者的话初始化的元素都成了0了·完全不能满足我的要求··各位大侠帮帮忙rnrn
ArrayList
我用 Random产生了一百个随机数。rn然后我用ArrayList保存。rn假如产生了 1,3,24,53,43....................rn我怎样才能让ArrayList 按照下面格式保存 ('1','3','24','53','43')rnrn当我用Iterator 迭代出来的时候又变成(1,3,24,53,43)这种样式...........rnrn请高手帮忙。。。急。。。。。。。。。。。。
ArrayList?
创建一个类GetNumber,在这里面生成10个随机数,用Math.random(),它产生一个(0,1)之间的double类型小数,然后写个方法,将这10个数装在一个ArrayList对象里面,注意这个方法的返回值是List,再写一个测试类TestNumber,在这个类里面,在这个类里面写一个方法,调用GetNumber的方法,计算这十个数的平均数,输出结果.
ArrayList原理分析及手写ArrayList
在面试过程中,会遇到ArrayList实现原理是怎么样,在什么情况会对集合进行扩容等问题;ArrayList相对于其它的集合是比较简单的了。在后面会将手写的ArrayList代码附上,在这之前我们需要了解ArrayList一些主要的成员变量以及原理。 1、主要的成员变量解释 /** * Default initial capacity. */ ...
关于在Java中使用foreach对ArrayList遍历抛出ConcurrentModificationException异常的疑惑。
[code=Java]rnpublic static void removeGradeLess(rn ArrayList arrayList,rn int grade) rn rn for(int i=0;i i = arrayList.iterator();rn while(i.hasNext())rn if(i.next().getGrade()StudentArrayListrn *rn * @author iCarnegiern * @version 1.0.0rn * @see Studentrn * @see StudentArrayListrn */rnpublic class TestStudentArrayList rnrn /* Standard output stream */rn private static PrintWriter stdOut =rn new PrintWriter(System.out, true);rnrn /* Standard error stream */rn private static PrintWriter stdErr =rn new PrintWriter(System.err, true);rnrn /* Variables that contains the test objects */rn private Student first;rn private Student second;rn private Student third;rn private Student fourth;rn private Student fifth;rn rn private Student firstArrayListTwo;rn private Student secondArrayListTwo;rn private Student thirdArrayListTwo;rn private Student fourthArrayListTwo;rn private Student fifthArrayListTwo;rn rn private ArrayList emptyArrayList;rn private ArrayList arrayList;rn private ArrayList arrayListTwo;rnrn /**rn * Tests methods of class @link StudentArrayListrn *rn * @param args not usedrn */rn public static void main (String args[]) rnrn stdOut.println("");rn stdOut.println("Testing class StudentArrayList...");rnrn TestStudentArrayList tester = new TestStudentArrayList();rnrn if (tester.testMakeArrayList() &rn tester.testMakeArrayListFromArray() &rn tester.testHasStudent() &rn tester.testCountGradeGreaterOrEqual() &rn tester.testGetMinGrade() &rn tester.testGetGradeAverage() &rn tester.testRemoveGradeLess() &rn tester.testDisplayAll()) rn stdOut.println("All tests passed");rn rn rnrn /**rn * Displays a message in the standard error stream if the value specifiedrn * by parameter condition is false.rn *rn * @param message the error message.rn * @param condition the test condition.rn * @return the value of conditionrn */rn public static boolean assertTrue(String message, boolean condition) rnrn if (! condition) rn stdErr.print("** Test failure ");rn stdErr.println(message);rnrn return false;rn else rnrn return true;rn rnrn rnrn /**rn * Displays a message in the standard error stream.rn *rn * @param message the error message.rn * @return falsern */rn public static boolean fail(String message) rnrn stdErr.print("** Test failure ");rn stdErr.println(message);rnrn return false;rn rnrn /** Assign the initial value to the test variables */rn private void setUp() rnrn first = new Student(10, "First", 100);rn second = new Student(20, "Second", 90);rn third = new Student(30, "Third", 80);rn fourth = new Student(40, "Fourth", 90);rnrn firstArrayListTwo = new Student(10, "First", 50);rn secondArrayListTwo = new Student(20, "Second", 90);rn thirdArrayListTwo = new Student(30, "Third", 80);rn fourthArrayListTwo = new Student(40, "Fourth", 80);rn fifthArrayListTwo = new Student(50, "Fifth", 90);rnrn emptyArrayList = new ArrayList();rnrn arrayList = new ArrayList();rn arrayList.add(first);rn arrayList.add(second);rn arrayList.add(third);rn arrayList.add(fourth);rnrn arrayListTwo = new ArrayList();rn arrayListTwo.add(firstArrayListTwo);rn arrayListTwo.add(secondArrayListTwo);rn arrayListTwo.add(thirdArrayListTwo);rn arrayListTwo.add(fourthArrayListTwo);rn arrayListTwo.add(fifthArrayListTwo);rn rnrn public boolean testRemoveGradeLess() rnrn setUp();rnrn boolean test = true;rnrn try rnrn StudentArrayList.removeGradeLess(emptyArrayList, 100);rn test = test && assertTrue("1, testing method removeGradeLess",rn emptyArrayList.size() == 0);rn rn StudentArrayList.removeGradeLess(arrayList, 90);rn test = test && assertTrue("2, testing method removeGradeLess",rn arrayList.size() == 3);rn test = test && assertTrue("3, testing method removeGradeLess",rn arrayList.get(0) == first);rn test = test && assertTrue("4, testing method removeGradeLess",rn arrayList.get(1) == second);rn test = test && assertTrue("5, testing method removeGradeLess",rn arrayList.get(2) == fourth);rn rn StudentArrayList.removeGradeLess(arrayListTwo, 90);rn test = test && assertTrue("6, testing method removeGradeLess",rn arrayListTwo.size() == 2);rn test = test && assertTrue("7, testing method removeGradeLess",rn arrayListTwo.get(0) == secondArrayListTwo);rn test = test && assertTrue("8, testing method removeGradeLess",rn arrayListTwo.get(1) == fifthArrayListTwo);rn catch (Exception e) rn test = fail("9, testing method removeGradeLess: " + e.toString());rn rnrn return test;rn rn[/code]rn检查时会报错误。抛出ConcurrentModificationException异常,有人能解释一下这是怎么回事嘛?rnrnrn
Arraylist
有2个ArrayList如下rn[code=C#]rn ArrayList al1 = new ArrayList();rn ArrayList al2 = new ArrayList();rnrn al1.Add("a");rn al1.Add("b");rn al1.Add("c");rn al1.Add("d");rnrn al2.Add("a");rn al2.Add("c");rn al2.Add("zz");rn al2.Add("a");rn al2.Add("b");rn al2.Add("a");rn al2.Add("c");rn[/code]rnrn现要求al1根据al2的值构建al3,当al1的值在al2中出现过2次或以上的,那么这个值就会被去掉:rn如这个例子中a和c在al2中出现了2次或以上,就会被去掉,最后的结果应是 b,drnrnal1和al2都比较大,请教该如何有效的写这个函数?
ArrayList alis = new ArrayList
这样用是什么意思?,有什么特殊含义没?
arraylist
java写的webservice接口,要求数据为arraylist 包括姓名、密码 ,用php的客户端调用,数据应该写什么格式?rn
ArrayList[]=new ArrayList[]?
ArrayList[] adUrls;rnprivate void GetAdUrl(WebBrowser[] webs)rn rn adUrls = new ArrayList[webs.Length];rn rn for (int i = 0; i < webs.Length;i++ )rn rn adUrls[i] = new ArrayList();rn Regex r = new Regex(Reg(webs[i].Url.Host), RegexOptions.IgnoreCase | RegexOptions.Compiled);rn Match m = r.Match(webs[i].DocumentText.ToLower());rn while (m.Success)rn rnrn if (!adUrls[i].Contains((webs[i].Url.ToString().Replace(GetSurf(webs[i].Url.Host), "")) + @"view.php?" + m.Value))rn rn adUrl[i]s.Add((webs[i].Url.ToString().Replace(GetSurf(webs[i].Url.Host), "")) + @"view.php?" + m.Value);rnrn rn elsern rnrn rn m = m.NextMatch();rn rn foreach (string str in adUrl[i])rn rn listBox1.Items.Add(str);rn rn rn rnlistBox1中什么都没有。ArrayList[]可不可以这么用啊!
arraylist .
arraylist .
ArrayList> 如何转换成ArrayList
如题,android 中 如何将ArrayList> 如何转换成ArrayList类型
集合遍历时删除元素异常(ConcurrentModificationException)分析
传统方式下的Collection在迭代集合时,不允许对集合进行修改。根据AbstractList的checkForComodification方法的源码,分析产生ConcurrentModificationException异常的原因 传统方式下的Collection在迭代集合时,不允许对集合进行修改。 根据AbstractList的checkForComodificati
nio的SELECTOR和多线程之间ConcurrentModificationException问题
private static Selector selector;rn staticrn try rn selector=Selector.open();rn catch (IOException e) rn e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.rn rn rn private InetSocketAddress socketAddress;rn private DatagramChannel channel = null;rnrnrn public void openDatagramChannel(String url, int port) throws Exception rn channel = DatagramChannel.open();rn channel.socket().setSoTimeout(10000);rn channel.configureBlocking(false);rn socketAddress = new InetSocketAddress(url, port);rn channel.connect(socketAddress);rn SelectionKey key = channel.register(selector, SelectionKey.OP_WRITE);rn rnrn public void closeDatagramChannel() throws Exception rn if (channel != null) rn SelectionKey key = channel.keyFor(selector);rn if (key != null) key.cancel();rn channel.socket().disconnect();rn channel.socket().close();rn channel.disconnect();rn channel.close();rn channel = null;rn rn rnrn public boolean connect(String host, int port) throws Exception rn try rn if (channel == null) openDatagramChannel(host, port);rn int num = selector.select();rn if (num == 0) return false;rn Set Keys = selector.selectedKeys(); //size=0?rn Iterator it = Keys.iterator();rn ByteBuffer buffer = ByteBuffer.allocateDirect(1024);rn if (it.hasNext()) rn SelectionKey k = (SelectionKey) it.next();rn if ((k.readyOps() & SelectionKey.OP_WRITE)rn == SelectionKey.OP_WRITE) rn //do somethingrn it.remove();rn rn rn finally rn closeDatagramChannel();rn rn return false; //To change body of implemented methods use File | Settings | File Templates.rn rn=============================================================rn多线程运行上面程序会报告ConcurrentModificationException。这个很明显,在一个SELECTOR的情况下,SELECTOR在被多线程改变的时候,就出现ConcurrentModificationException错误。rnrn另外一个办法是每次openDatagramChannel的开一个SELECTOR。但这个问题在多线程,高并发的情况下引起了SELECTOR占据了所有文件句柄问题(65536),具体见http://www.zxbc.cn/html/20080401/32982.html。rnrn那么,在高并发的情况下。是开多个SELEcTOR,还是开一个?只一个,就出现上面情况ConcurrentModificationException.这个如何解决?rnrnrn请HELP一下,一个人搞不定了
ConcurrentModificationException异常出现原因以及解决方法
今天在开发过程中遇到一个异常叫ConcurrentModificationException,这个异常用我的白话翻译是叫同时修改异常。 这个异常是怎么出现的呢,先看看已下的代码: @Override public void onGetModel(List modelList) { if (modelList != null) { this.i
解决数组迭代 ConcurrentModificationException异常的方法(复制)
// 先获取一级回复 List&lt;Reply&gt; replies = dao.getReply(targetId); // 解决数组迭代 ConcurrentModificationException异常的方法(复制) List&lt;Reply&gt; copyReplies = new ArrayList&lt;Reply&gt;();...
java集合(2)—— ConcurrentModificationException异常原因和解决方法
以下的内容摘抄自:http://www.cnblogs.com/dolphin0520/p/3933551.html ConcurrentModificationException异常出现的原因 使用集合的时候,通常希望遍历到需要修改的集合后,直接利用集合对象的remove方法直接删除或者修改对应的值。但是!这种方法是不可行的,调试过的小伙伴儿应该知道,这样做会抛出一个Concurrent...
遍历删除容易出现的ConcurrentModificationException问题解决方法
删除列表中的某些符合条件的对象,一不小心容易出现ConcurrentModificationException异常,如以下代码就会出现问题: for(CourseInfo info : myCourseList){ if(info.isChecked){ myCourseList.remove
多线程操作LinkedList导致ConcurrentModificationException异常
由于需要下载多张图片,程序中有一LinkedList listLoadingUrl记录正在联网下载的url链接。rnrn线程A下载完后,在线程结束之前要执行listLoadingUrl.remove(imgUrl);rn如果有新的图片请求,会执行listLoadingUrl.contains(imgUrl),如果存在该图片的链接,则表示已经在下载了。rn在执行contains(imgUrl)的时间段内,一旦线程A执行remove操作,则抛出了:ConcurrentModificationException异常。rnrn请问这种问题该如何解决呢?
相关热词 c# 线程结束时执行 c# kb mb 图片 c# 替换第几位字符 c#项目决定成败 c# 与matlab c# xml缩进 c#传感器基础 c#操作wps c# md5使用方法 c# 引用父窗口的组件