JSF Generic entity converter is not ThreadSafe

跟風遠走 提交于 2019-12-24 14:01:10

问题


I have been using the famouse entityConverter for a long time, but today I realised that this is not thread safe and it can generate concurrences errors.

If one thread adds a element in the Hash, and another reads the hash at the same time, a java.util.ConcurrentModificationException exception will be threw

Somebody can confirm this problem? Thanks

The converter code : taken from BalusC post Generic JSF entity converter

@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) {
        for (Entry<Object, String> entry : entities.entrySet()) {
            if (entry.getValue().equals(uuid)) {
                return entry.getKey();
            }
        }
        return null;
    }

}

来源:https://stackoverflow.com/questions/16819014/jsf-generic-entity-converter-is-not-threadsafe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!