ConcurrentModificationException 的异常分析

今日运行一段如下代码
List<;Person> pList = ...
for(Person person : pList){
  if(person.getGender()==Gender.MALE){
    pList.remove(person);
  }
}

报出的异常为 java.util.ConcurrentModificationException 异常
经查找资料


public class ConcurrentModificationExceptionextends RuntimeException
当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。 

例 如,某个线程在 Collection 上进行迭代时,通常不允许另一个线性修改该 Collection。通常在这些情况下,迭代的结果是不明确的。如 果检测到这种行为,一些迭代器实现(包括 JRE 提供的所有通用 collection 实现)可能选择抛出此异常。执行该操作的迭代器称为快速失败  迭代器,因为迭代器很快就完全失败,而不会冒着在将来某个时间任意发生不确定行为的风险。 

注意,此异常不会始终指出对象已经由不同 线程并发修改。如果单线程发出违反对象协定的方法调用序列,则该对象可能抛出此异常。例如,如果线程使用快速失败迭代器在 collection 上迭代时直接修改该 collection,则迭代器将抛出此异常。 

注 意,迭代器的快速失败行为无法得到保证,因为一般来说,不可能对是否出现不同步并发修改做出任何硬性保证。快速失败操作会尽最大努力抛出  ConcurrentModificationException。因此,为提高此类操作的正确性而编写一个依赖于此异常的程序是错误的做法,正确做法 是:ConcurrentModificationException 应该仅用于检测 bug。


当使用 fail- fast iterator 对 Collection 或 Map 进行迭代操作过程中尝试直接修改 Collection / Map 的内容时,即 使是在单线程下运行, java.util.ConcurrentModificationException 异常也将被抛出。 

   Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当 原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则  Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
  所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。
   有意思的是如果你的 Collection / Map 对象实际只有一个元素的时候,  ConcurrentModificationException 异常并不会被抛出。这也就是为什么在 javadoc 里面指出:  it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.

修改后的代码如下:

Iterator<Person> it = pList.iterator();
while(it.hasNext()){
  if(it.next().getGender()==Gender.MALE){
    it.remove();
  }
}  

异常分析

04-24

HTTP Status 500 - rnrn--------------------------------------------------------------------------------rnrntype Exception reportrnrnmessage rnrndescription The server encountered an internal error () that prevented it from fulfilling this request.rnrnexception rnrnjava.lang.reflect.InvocationTargetExceptionrn sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)rn sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)rn java.lang.reflect.Method.invoke(Unknown Source)rn com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)rn com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)rn org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)rn com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)rn com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)rn com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)rn org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:rnrn

异常分析..?

03-27

java.lang.ClassCastException:weblogic.transaction.internal.ServerTransactionImplrnrnat weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2253)rn at weblogic.utils.io.ObjectStreamClass.writeFields(ObjectStreamClass.java:413)rn at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:235)rn at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:225)rn at weblogic.corba.utils.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:182)rn at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1957)rn at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1992)rn at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2253)rn at weblogic.jdbc.common.internal.RmiDataSource_WLSkel.invoke(Unknown Source)rn at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589)rn at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:224)rn at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:479)rn at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)rn at weblogic.security.service.SecurityManager.runAs(Unknown Source)rn at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:475)rn at weblogic.rmi.internal.BasicServerRef.access$300(BasicServerRef.java:59)rn at weblogic.rmi.internal.BasicServerRef$BasicExecuteRequest.run(BasicServerRef.java:1016)rn at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)rn at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)rnrn我在做JTA时,出现这个异常信息,请问是怎么回事?rn急需答案!rn

ConcurrentModificationException问题?

12-02

[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指的会是什么?

SoapConnector->EndMessage();异常分析

08-28

HRESULT hr;rn tryrn rn rn CComPtr SoapConnector;rn //创建SoapConnector类的对象rn SoapConnector.CoCreateInstance(CLSID_HttpConnector30);rn rn //指定Web服务的地址rn SoapConnector->put_Property(CComBSTR("EndPointURL"),_variant_t("http://172.18.70.32:82/MobileService/"));rn rn //与Web服务连接rn hr=SoapConnector->Connect();rn rn //指定Web服务完成的操作rn SoapConnector->put_Property(CComBSTR("SoapAction"),_variant_t(_T("http://tempuri.org/IMobileService/GetCXY")));rn rn //准备发送消息给Web服务rn SoapConnector->BeginMessage();rn rn // 创建SoapSerializer对象rn CComPtr Serializer;rn Serializer.CoCreateInstance(CLSID_SoapSerializer30);rn rn // 将serializer连接到connector的输入字符串rn IStreamPtr pStream;rn SoapConnector->get_InputStream(&pStream);rn Serializer->Init(_variant_t((IUnknown*)pStream));rn rn // 创建SOAP消息rn Serializer->StartEnvelope(CComBSTR("Soap"),CComBSTR(""),CComBSTR(""));rnrn Serializer->StartBody(CComBSTR(""));rn rn Serializer->StartElement(CComBSTR("GetXY"),CComBSTR("http://tempuri.org/"),CComBSTR(""),CComBSTR("Soap")); // 消息函数名称rn rn Serializer->StartElement(CComBSTR("phone"),CComBSTR(""),CComBSTR(""),CComBSTR("Soap")); // 函数参数rn rn Serializer->WriteString(CComBSTR("13031040117")); //参数处理 rn rn Serializer->EndElement();rn rn Serializer->EndElement();rn rn Serializer->EndBody();rnrn Serializer->EndEnvelope();rn rn //消息真正地发给Web服务rn [color=#FF0000]hr = SoapConnector->EndMessage(); //如果访问不到WebService或网速慢,就会导致程序异常。[/color] if (FAILED(hr))rn rn return ;rn rn // 读取响应rn CComPtr Reader;rn Reader.CoCreateInstance(CLSID_SoapReader30);rn rn // Connect the reader to the output stream of the connector object.rn IStreamPtr pStream2;rn SoapConnector->get_OutputStream(&pStream2);rn这里报错. 网上查说是访问不到这个webs, 或者网速慢, 可我的webs 部署在本机啊rn另外请看下我的wsdl 描述吧rn

异常分析,listenerstart异常 求解。

11-28

十一月 28, 2017 10:22:16 下午 org.apache.catalina.core.StandardContext listenerStartrnSEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListenerrnorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [spring/applicationContext-db.xml]: Invocation of init method failed; nested exception is java.lang.OutOfMemoryError: PermGen spacern at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)rn at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)rn at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)rn at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)rn at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)rn at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)rn at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)rn at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:546)rn at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:872)rn at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)rn at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)rn at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)rn at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)rn at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4323)rn at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4771)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)rn at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:785)rn at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:763)rn at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:558)rn at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1124)rn at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:1047)rn at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:542)rn at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1390)rn at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:355)rn at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)rn at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:89)rn at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:312)rn at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:292)rn at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:998)rn at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:772)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)rn at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)rn at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:275)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)rn at org.apache.catalina.core.StandardService.startInternal(StandardService.java:424)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)rn at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:648)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)rn at org.apache.catalina.startup.Catalina.start(Catalina.java:576)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)rn at java.lang.reflect.Method.invoke(Method.java:601)rn at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)rn at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:415)rnCaused by: java.lang.OutOfMemoryError: PermGen spacernrnrnrnrnrn十一月 28, 2017 10:22:17 下午 org.apache.catalina.core.StandardContext listenerStartrnSEVERE: Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListenerrnjava.lang.OutOfMemoryError: PermGen spacern at java.lang.ClassLoader.findBootstrapClass(Native Method)rn at java.lang.ClassLoader.findBootstrapClassOrNull(ClassLoader.java:1061)rn at java.lang.ClassLoader.loadClass(ClassLoader.java:412)rn at java.lang.ClassLoader.loadClass(ClassLoader.java:410)rn at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)rn at java.lang.ClassLoader.loadClass(ClassLoader.java:356)rn at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1579)rn at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)rn at com.sun.faces.config.WebConfiguration.(WebConfiguration.java:63)rn at com.sun.faces.config.WebConfiguration.getInstance(WebConfiguration.java:152)rn at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:279)rn at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4323)rn at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4771)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)rn at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:785)rn at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:763)rn at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:558)rn at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1124)rn at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:1047)rn at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:542)rn at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1390)rn at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:355)rn at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)rn at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:89)rn at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:312)rn at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:292)rn at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:998)rn at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:772)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)rn at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:990)rn at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:275)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)rnrnrnSSH出现以下异常。用了maven,pom没错。包没错。

一些jsp异常分析理解

12-15

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>rn<%@ page import="org.wangsheng.beans.Identify;"%>rn<%rnString path = request.getContextPath();rnString basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";rn%>rnrnrnrn rn rn rn My JSP 'control.jsp' starting pagern rn rn rn rn rn rn rnrn rn rn rn rn 数据源: rn 表格名: rn <% String contion = request.getParameter("con");rn String math = request.getParameter("amount");rn //出路amount 为空rn if(null == math || math.equals(""))rn response.sendRedirect("toollist.jsp");rn return;rn rn rn rn else //判断某math是否为rn int amount = Identify.getamount(math);//这个方法是我在另一个类的static方法rn if(amount==0)rn response.sendRedirect("toollist.jsp"); rn return;rn rn rn else if(contion.equals("create")) rn for(int j=0;jrn 属性名<%=j%>rn 类型: null:rn rn defaultnot null rn rn key:rn defaultprimary rn rn default: rn <%rn rn rn rn %> rn <%--下面一个部分应该是对修改数据表进行操作--%>rn rn rn rn rn rn[/code]rn出现的异常是rn>exception org.apache.jasper.JasperException: An exception occurred processing JSP page /control.jsp at line 51rn rn48: //判断某math是否为rn49: int amount = Identify.getamount(math);rn50: if(amount==0)rn51: response.sendRedirect("toollist.jsp");rn52: rn53: rn54: rn rn rnStacktrace:rn org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)rn org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:410)rn org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)rn org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn root cause java.lang.IllegalStateExceptionrn org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435)rn org.apache.jsp.control_jsp._jspService(control_jsp.java:111)rn org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)rn org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)rn org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn note The full stack trace of the root cause is available in the Apache Tomcat/6.0.20 logs.rnrn这个jsp可以在浏览器中正确显示,但是查看源代码的时候,就会这些异常就会在代码中rnrn帮忙分析一下,谢谢rn

ConcurrentModificationException求各位大哥帮忙!

06-25

错误信息: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

nio的SELECTOR和多线程之间ConcurrentModificationException问题

01-20

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 的问题,关于一个简单连接池的问题

04-09

我写了一个关于数据库连接池的一个简单类,用List 装了15 个Connection rn代码类似下面的简单例子rn 我用Iterator 迭代的时候抛出java.util.ConcurrentModificationException异常,rn后来我改用普通 的for 循环,不再出现此种情况,但会不会出现潜在的线程问题?rn下面 是改后的代码rnrn[code=Java]rnpackage utils;rnrnimport java.sql.Connection;rnimport java.sql.DriverManager;rnimport java.sql.PreparedStatement;rnimport java.sql.ResultSet;rnimport java.sql.SQLException;rnimport java.sql.Statement;rnimport java.util.ArrayList;rnimport java.util.List;rnrnpublic class DBUtils rn private static DBUtils instance = new DBUtils();rnrn static List conns = new ArrayList();rnrn static rn init();rnrn rn//初始化十五个connection 放入list 中rn private static void init() rn // 向 conns加入15个 connectionrn Connection conn = null;rnrn try rn Class.forName("com.mysql.jdbc.Driver");rnrn catch (ClassNotFoundException e) rn e.printStackTrace();rn rnrn for (int i = 0; i < 15; i++) rn try rn conn = DriverManagerrn .getConnection("jdbc:mysql://localhost:3307/bbs?user=root&password=root");rnrn catch (SQLException e) rn e.printStackTrace();rn rn conns.add(conn);rn rn rnrn public static DBUtils getInstance() rn return instance;rn rnrn public Connection getConn() rn Connection conn = null;rnrn for (int i = 0; i < conns.size(); i++) rnrn conn = conns.get(0);rnrn try rn if (conn == null || conn.isClosed()) // 如果,移除此关闭的连接,并重新加入一个连接;rn conns.remove(conn);// 移除已关闭的联结rn //rn closeConnActually(conn);rn conn = DriverManagerrn .getConnection("jdbc:mysql://localhost:3307/bbs?user=root&password=root");rn conns.add(conn);rnrn else // 否则,此连接未被关闭则rnrn conns.remove(conn);rn return conn;rnrn rn catch (SQLException e) rn e.printStackTrace();rn rnrn rn init();rnrn return getConn();rnrn rn rn rn //把conn 重新放回conns(List) 中//并未真正关闭rn public void close(Connection conn) rn if (conn != null) rn try rn if (!conn.isClosed()) rn // 将此连接重新放入conns 以备重用rn conns.add(conn);rn rn catch (SQLException e) rn e.printStackTrace();rn rn rn rn//真正关闭一个连接 rn public void closeConnActually(Connection conn) rn if (conn != null) rn try rn if (!conn.isClosed()) rn conn.close();rn rn catch (SQLException e) rn e.printStackTrace();rn rn rn rnrn rn rn rnrnrn[/code]

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试