gpt4 book ai didi

java - JSF 实体转换器 ConcurrentModificationException

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:39 25 4
gpt4 key购买 nike

我在我的项目中使用通用实体转换器。我注意到有时转换器会抛出 java.util.ConcurrentModificationException还有一个4岁Post没有答案。

我尝试使用 Iterator 而不是普通的 for-loop 但它没有帮助。

有没有办法创建线程安全的转换器?

@FacesConverter(value = "entityConverter")
public class EntityConverter implements Converter {

private static Map<Object, String> entities = new WeakHashMap<Object, String>();

@Override
public String getAsString(FacesContext context, UIComponent component, Object entity) {
synchronized (entities) {
if (!entities.containsKey(entity)) {
String uuid = UUID.randomUUID().toString();
entities.put(entity, uuid);
return uuid;
} else {
return entities.get(entity);
}
}
}

@Override
public Object getAsObject(FacesContext context, UIComponent component, String uuid) {

Iterator<Map.Entry<Object, String>> tempIt = entities.entrySet().iterator();
while (tempIt.hasNext()) {
Map.Entry<Object, String> nextObj = tempIt.next();
if (nextObj.getValue().equals(uuid)) {
return nextObj.getKey();
}
}

return null;
}

}

最佳答案

与其他方法一样,将 getAsObject 的主体包装在与 entities 同步的 block 中。

关于java - JSF 实体转换器 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50287089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com