Why @Singleton over @ApplicationScoped in Producers?

不问归期 提交于 2019-12-10 13:39:37

问题


LoggerProducer.java is a class used to produce Loggers to be injected in CDI beans with:

@Inject 
Logger LOG;

Full code:

import javax.ejb.Singleton;

/**
 * @author rveldpau
 */
@Singleton
public class LoggerProducer {

    private Map<String, Logger> loggers = new HashMap<>();

    @Produces
    public Logger getProducer(InjectionPoint ip) {
        String key = getKeyFromIp(ip);
        if (!loggers.containsKey(key)) {
            loggers.put(key, Logger.getLogger(key));
        }
        return loggers.get(key);
    }

    private String getKeyFromIp(InjectionPoint ip) {
        return ip.getMember().getDeclaringClass().getCanonicalName();
    }
}

QUESTION: can @Singleton be safely turned into @ApplicationScoped ?

I mean, why would anyone want an EJB here ? Are there technical reasons, since no transactions are involved, and (AFAIK) it would be thread-safe anyway ?

I'm obviously referring to javax.enterprise.context.ApplicationScoped, not to javax.faces.bean.ApplicationScoped.


回答1:


The @Singleton annotation provides not only transaction but also thread-safety by default. So if you will replace it with @ApplicationScoped, you will loose the synchronization. So in order to make it properly you need to do like this:

@ApplicationScoped
public class LoggerProducer {

   private final ConcurrentMap<String, Logger> loggers = new ConcurrentHashMap<>();

   @Produces
   public Logger getProducer(InjectionPoint ip) {
      String key = getKeyFromIp(ip);
      loggers.putIfAbsent(key, Logger.getLogger(key));
      return loggers.get(key);
   }

   private String getKeyFromIp(InjectionPoint ip) {
     return ip.getMember().getDeclaringClass().getCanonicalName();
  }
}

Also you can make it completely without any scope if you make the map as static



来源:https://stackoverflow.com/questions/27103517/why-singleton-over-applicationscoped-in-producers

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