Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF Entityconverter ConcurrentModificationException

Tags:

java

jsf

I'm using a generic entity converter in my Project. I've noticed that sometimes the converter throws a java.util.ConcurrentModificationException There is also a 4 years old Post which has no answer.

I tried to use Iterator instead of a plain for-loop but it didn't helped.

Is there a way to create a thread-safe 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) {

        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;
    }

}
like image 248
Mihawk Avatar asked Jun 12 '26 14:06

Mihawk


1 Answers

Wrap the body of getAsObject in a block synchronized on entities, as in the other method.

like image 100
Andy Turner Avatar answered Jun 15 '26 04:06

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!