0

I need to create a Thread in Spring that loops forever and blocks on a LinkedBlockingQueue.take() to process an object in it (a Controller puts objects in that queue). My piece of code works fine if being processed inside the @Controller. However, now that I moved it into the Thread I get multiple LazyInitializationException from Hibernate. In a nutshell the pseudo-code skeleton of my thread is:

@Component
public class AsynchronousConsumer implements Runnable
{
   @Autowire
   // Service Layer and other goodies (all correctly injected)

   @PostConstruct
   public void init(){
      (new Thread(this)).start();
   }

   // Note that an @Controller action is placing MyBean in the queue 
   protected static LinkedBlockingQueue<MyBean> queue = new LinkedBlockingQueue<MyBean>();

   @Override
   public void run()
   {
      while(true)
      {
         MyBean myBean = queue.take();
         this.processBean(myBean); // do the processing
      }    
   }    
   void processBean(MyBean m)
   {
      // Hybernate exceptions happen when retrieving objects from the DB
   }
}

Am I doing something wrong here? How should I start my thread so it is fully Spring/Hibernate aware?

  • lazy initialization occurs when no hibernate session is bound to the thread. perhaps you should post more info on your transaction configuration. open session in view? @Transactional annotations? ... that kind of stuff. – G-Man Jul 18 '12 at 13:54
  • @G-Man could you be more specific, I would appreciate some pointers to some documentation, tutorial, examples... –  Jul 18 '12 at 14:10
  • There is no clearcut solution because you haven't provided all the required information. All i know is somewhere in your application is a piece of code that fails because no live session is bound to the thread when it tries to lazy load something. As long as i don't know where the issue occurs, and what the general configuration of the application is i'm just guessing. So please provide aditional information about your hibernate configuration. Its possible this issue can be solved by injecting a sessionfactory in your thread and create and open session each cycle in your while loop. – G-Man Jul 23 '12 at 14:26

1 Answers1

1

i am not sure need to create your own thread i think yous should be able to do this by having task scheduler and executor in spring. Task & Scheduling

Jigar Parekh
  • 6,163
  • 7
  • 44
  • 64