java.util.ConcurrentModificationException异常排查
java.util.ConcurrentModificationException对于这个异常我们一般会认为是在遍历list的时候对这个list做了add,remove等修改操作造成的,最近在线上日志偶尔发现了这个异常,完整异常如下:
java.util.ConcurrentModificationException: null
at java.util.ArrayList.sort(ArrayList.java:1462)
at java.util.Collections.sort(Collections.java:175)
at com.xxx.xxx.xxx.xxx(xxx.java:17)注:这是业务代码所以用‘xxx’代替了
at com.xxx.xxx.xxx.xxx(xxx.java:65)
at sun.reflect.GeneratedMethodAccessor237.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
代码如下:(原有代码比较复杂,写个类似demo代替)
public class CmeTest {
private static Map<String,List<Integer>> map = new HashMap<>();
public static void main(String[] args) {
buildMap();
Runnable run = new Runnable() {
@Override
public void run() {
Collections.sort(map.get("a"));
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
for(int i=0 ;i<1000;i++) {
pool.execute(run);
}
pool.shutdown();
}
private static void buildMap() {
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
map.put("a", list1);
}
代码的主要逻辑就是并发地对一个list进行排序。查看Collections.sort()的源码如下:
1 @Override
2 @SuppressWarnings("unchecked")
3 public void sort(Comparator<? super E> c) {
4 final int expectedModCount = modCount;
5 Arrays.sort((E[]) elementData, 0, size, c);
6 if (modCount != expectedModCount) {
7 throw new ConcurrentModificationException();
8 }
9 modCount++;
10 }
重点看第6,10行,当第一个线程排序完成,执行完第9行时第二个线程正好执行到第6行,这时候就会抛出ConcurrentModificationException,所以对于全局的list,做并发排序的时候需要额外注意一下。解决方法有两个:
1.加锁
2.创建新的list,再将全局list的数据addAll到新list中,对新list排序