-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: EntityListener and Singleton
PostPosted: Wed Jun 18, 2014 8:30 am 
Beginner
Beginner

Joined: Sat Feb 16, 2008 3:09 pm
Posts: 24
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.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.