Search code examples
javamultithreadingthread-safetyejbmessage-driven-bean

Spawning new java threads with in Message Driven Bean ( MDB)


Can I start /spawn new java thread from within a MDB? I have a requirement to do some parallel processing from code in MDB and then return the control back to MDB.

Requirement: Message come to MDB , then some processing of code. Then two new slave thread are started which do some parallel work. Till then MDB is waiting. when threads finish the work. Then control is returned back to MDB, which completes the the related final/cleanup work.

Is it good idea to start a new thread ( Runnable) from MDB? If not then what should be the alternative?


Solution

  • Starting new threads with in MDB is bad practice. It will work but the new threads are not in control of application container so can behave unpredictably. They can even mess-up the thread management which container is trying to maintain. Worst affect is if the application is deployed in cluster then user defined threads will fail miserably.

    In your scenario : Instead of starting new threads , create new MDB with logic of thread ( This way it will be managed by contaner now) then send message to these new MDB. If you want the control back to parent MDB then, I think , use your parent MDB in global transactional so that parent MDB will wait for child MDB to finish and control will return back.