这可能是重复的问题,但我在ConcurrentModificationException中有点混淆。我在堆栈上经历了一些其他问题Overflow也有一些与如何避免ConcurrentModificationException相关的文章。我知道在循环收集和修改相同时会发生此异常(最常见的问题是remove
)。
但在我的情况下,我只是在foreach
上循环(java.util.Set
)然后我得到了这个例外。
此外,我总是没有得到这个例外,当我在这个场景中使用Jmeter
(5秒内150个用户)加载我的Web应用程序测试时,我遇到异常
这是我的代码,我根据日志文件中的堆栈跟踪获取异常
public static Map<String, String> getMessageMap(Locale locale) {
Properties properties;
Set<Object> objkeys;
Map<String, String> messageMap = null;
if (messageMap == null) {
messageMap = new HashMap<String, String>();
// 1 Get properties file.
properties = Utility.loadPropertiesFile(locale); // this method return properties from static veriable
// 2 Get all keys of properties file.
objkeys = properties.keySet();
// 3 Add all key values into map.
for (Object key : objkeys) { caught exception here
String keyName = key.toString();
if (keyName.contains("global.")) {
messageMap.put(keyName, properties.getProperty(keyName));
}
}
}
return messageMap;
}
根据日志文件ConcurrentModificationException发生在第for (Object key : objkeys)
行
这是堆栈跟踪中的一些行
java.util.ConcurrentModificationException
at java.util.Hashtable$Enumerator.next(Unknown Source)
at com.utilities.MKCLUtility.getMessageMap(Utility.java:164)
at com.utilities.MKCLUtility.addMessage(Utility.java:49)
at com.controllers.LoginController.loginPost(LoginController.java:132)
我该怎么做才能避免这种情况?以及为什么发生这种异常虽然我没有修改集合。
更新代码
Iterator<Object> iterator = objkeys.iterator();
while (iterator.hasNext())
{
String keyName = iterator.next().toString();
if (keyName.contains("global.")) {
messageMap.put(keyName, properties.getProperty(keyName));
}
}
答案 0 :(得分:0)
根据问题评论的指导,我将代码更改为:
public static Map<String, String> getMessageMap(Locale locale) {
Properties properties;
Set<Object> objkeys;
if (messageMap == null) {
messageMap = new HashMap<String, String>();
// 1 Get properties file.
properties = MKCLUtility.loadPropertiesFile(locale);
// 2 Get all keys of properties file.
objkeys = properties.keySet();
// 3 Add all key values into map.
Iterator<Object> iterator = objkeys.iterator();
while (iterator.hasNext())
{
String keyName = iterator.next().toString();
if (keyName.contains("global.")) {
messageMap.put(keyName, properties.getProperty(keyName));
}
}
}
return messageMap;
}
我将messageMap
设为静态,因此,第一次请求时此函数会检查null
是否为空,然后messageMap
填充然后为下一个请求它将直接返回{{1} }}
通过这个ConcurrentModificationException得到解决。
但是如果你想给他们一些建议,那么我想知道Plzz。
答案 1 :(得分:-2)
您在迭代它的键集时修改messageMap
地图。这就是您收到邮件的原因。只需收集ArrayList
对象中的匹配键,然后对其进行迭代并修改messageMap
映射。
编辑:
该例外实际上指的是messageMap
而不是properties
。这两个是否以任何方式相关(公共密钥)。此处未显示的代码是否也会迭代messageMap
?