Reputation:
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?
Upvotes: 0
Views: 885
Reputation: 6273
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
Upvotes: 1