Hello,
In an JSE application
I have an EntityListener which references a Singleton class. This Singleton takes some time to instantiate (it references another Singleton wich instantiates the EntityManagerFactory).
The Singleton
Code:
public class UserService {
private final static Logger log = Logger.getLogger(UserService.class);
/*
* Singleton
*/
private static UserService instance = new UserService();
private UserService() {
log.info("****************** Creating User Service *********************");
PersistenceService persistenceService = PersistenceService.getInstance();
EntityManagerFactory emf = persistenceService.getEntityManagerFactory();
this.sachbearbeiterDAO = new SachbearbeiterDAOBean(emf);
}
public static UserService getInstance() {
return instance;
}
...
The entity Listener
Code:
public class AuditListener {
private final static Logger log = Logger.getLogger(AuditListener.class);
private UserService userService;
public AuditListener() {
super();
this.userService = UserService.getInstance();
log.info("Audit Listener created");
}
@PrePersist
public void prePersist(Object o) {
if (o instanceof WRObjekt) {
WRObjekt wrObjekt = (WRObjekt) o;
setUser(wrObjekt);
setDate(wrObjekt);
}
}
....
When running tests in some situations I get a null pointer exception because the userService in AuditListener is null.
How is this even possible?
Also when running my application I see that more than one instance of UserService is created.
I have tried several different versions of the synchronized Singleton pattern but none really works.
I would greatly welcome any suggestions.