下面的代码由线程池执行。首先,地图不是并发的,所以我已经改变了它,但我仍然在第二行得到修改异常。为了使这段代码成为线程安全的,我应该进行哪些更改?
ConcurrentHashMap<String, Account> entriesOnFile = IniReaderHelper.load();
for (Map.Entry<String,Account> entryFromFile: entriesOnFile.entrySet())
{
EntryWrapper wrapperFromEntriesFile = new EntryWrapper(entryFromFile.getValue());
if (wrapperFromEntriesFile.getName().equals(entryName))
{
Tracer.info("Found matching entry from the entries file for +'" + entryName + "'");
synchronized(this)
{
context.put(RequestServices.ENTRY_WRAPPER, wrapperFromEntriesFile);
}
entry = wrapperFromEntriesFile;
break;
}
}
更多信息:下面是返回地图的 .load() 函数的代码:
static public ConcurrentHashMap<String, Account> load() throws Exception
{
BufferedReader reader = null;
accounts.clear();
try
{
reader = new BufferedReader(new FileReader(getEntriesFile()));
Account current = null;
String accountName;
String line;
while ((line = reader.readLine()) != null)
{
... do stuff here then adding entry to the amp
accounts.put(accountName, current);
}
}
finally
{
if (reader != null)
reader.close();
}
return accounts;
}
这是堆栈跟踪:
error code [1] : java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at .....call(AsyncCommand.java:78)
堆栈跟踪指向第二行('for'循环),它写“EntryIterator.next”,所以这不意味着我应该改变:
for (Map.Entry<String,Account> entryFromFile: entriesOnFile.entrySet())
至
for (ConcurrentHashMap.Entry<String,Account> entryFromFile: entriesOnFile.entrySet())
这是“帐户”的声明
private static ConcurrentHashMap<String, Account> accounts = new ConcurrentHashMap<String, Account>();