1

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

}
Community
  • 1
  • 1
Mauricio
  • 628
  • 5
  • 9
  • Sorry for the delay I didn't realize about this comment, I observed this problem on a production environment. 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 as I said. If my comment sounds rude maybe is for my rusty english, i'm only trying to show and discuss a problem. – Mauricio Mar 17 '14 at 16:41

0 Answers0