Java – why does @ singleton exceed @ applicationscope in producers?
•
Java
LoggerProducer. Java is a class for generating loggers to be injected into CDI beans:
@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: @ singleton can safely become @ applicationscope?
I mean, why would anyone want to use EJB here? Is there a technical reason because no transactions are involved and (AFAIK) is thread safe anyway?
I obviously mean javax enterprise. context. Applicationscope, not javax faces. bean. ApplicationScoped.
Solution
@Singleton annotation provides not only transaction but also thread safety by default Therefore, if you replace it with @ applicationscope, you will lose synchronization So to make it right, you need to do 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();
}
}
If you set the map to static, you can also have no range at all
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
