Java.util.Timer vs EJB TimerBean

I need to implement a simple Timer task for the following scenario -

method1(){ ..... if(success){ trigger method2 for next 30 min every 15 sec } } 

I implemented this code using java.util.Timer and java.util.TimerTask and its performance. However, my code will eventually be deployed as a web service on the Glassfish server. So I want to know if there will be any problems with the glass fish container, as I indirectly use the threads through the timer.

I'm also not sure if I need an EJB Timer Bean. Can anyone advise what are the pros and cons of both approaches?

+4
source share
2 answers

As with most all EJBs, the biggest difference between the two methods is transactions. Timer EJB is an EJB, so each call will be a unique transaction, and the container will manage all these details for you.

A topic, especially if created from an EJB, will have an undefined transactional state. Most containers associate a lot of context with the current executable thread, especially the transactional state, this is one of the reasons (among other things) that self-consistent threads are a bad idea in an EJB container. Container context information may be missing or corrupt.

For an EJB timer, you can easily create one that fires every 15 seconds, but you will need to track and cancel it manually after 30 minutes. You can use ScheduleExpression to express the โ€œevery 15 s for 30 mโ€ rule, but you still need to cancel the timer at the end (and this, frankly, will work more to properly create this expression). Itโ€™s easier to just put the start time in the Timer information, which will tell him when it will start, and then can complete itself on the last run.

In the days leading up to Java EE 6, timers were constant and kept reloading the container (although it did NOT reinstall the application). Now perseverance is optional, so you need to pay attention to this detail.

If this method was to be run from the Web layer (rather than the EJB layer), the flow restrictions are relaxed, or you can use Quartz Timer.

But EJB timers are pretty good, and better for Java EE 6. I would use EJB Timer, but I was comfortable with them, and they worked with more difficult to use pre-Java EE 6 for some time. If you are at the EJB level for the whole process, I would of course use them.

+2
source

The EJB specification warns of a custom encoding (or third party).

A bean should not attempt to manage flows. A bean should not attempt to start, stop, pause, or resume a stream or change the priority or name of a stream. A bean should not attempt to manage thread groups. ( 21.2.2 Programming restrictions , EJB 3.1 specification)

EJB Timer bean is preferred.

+5
source

All Articles