4

I have to implement a simple Timer task for following scenario -

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

I have implemented this code using java.util.Timer and java.util.TimerTask and its working fine. However, my code will eventually be deployed as a web service in glassfish server. So I want to know will it create any problems due to glassfish container as I am indirectly using threads via Timer.

I am also not sure whether I should EJB Timer Bean. Can somebody please advise what are the pros and cons of both the approaches?

Pradeep Simha
  • 17,683
  • 18
  • 56
  • 107
csn
  • 376
  • 7
  • 18

2 Answers2

5

EJB specification warns about user-coded (or third side-coded) threading.

The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups. (21.2.2 Programming Restrictions, EJB 3.1 specification)

EJB Timer Bean is preferred.

Alex Kreutznaer
  • 1,170
  • 8
  • 18
2

As with most everything EJB, the biggest distinction between the two techniques is transactions. Timer EJBs are, well, EJBs, so each invocation will be a unique transaction, and the container will manage all of those details for you.

The thread, especially if created from within an EJB, will have an undetermined transactional state. Most containers associate a lot of context with the currently executing thread, especially transactional state, this is one reason (among others) that self made threads are a bad idea in an EJB container -- the containers context information can be missing or corrupted.

For an EJB Timer, you can readily create one that that fires every 15s, but you will need to keep track and cancel it manually after 30 minutes. You could use a ScheduleExpression to express the "every 15s for 30m" rule, but you'll still need to cancel the timer at the end (and it would frankly be more work to create that expression properly). It's easier to just put a start time in the Timers Info that tells it when it started, then it can terminate itself on the last run.

In the days before Java EE 6, Timers were persistent and survived container restarts (though NOT application redeploys). Now, the persistence is optional, so you'll need to pay attention to that detail.

If this method were to be triggered from the Web tier (and not the EJB tier), the threading restrictions are relaxed, or you could use the Quartz Timer.

But the EJB timers are pretty good, and better for Java EE 6. I would use the EJB Timer, but I'm comfortable with them and have worked with the harder-to-use pre-Java EE 6 ones for some time. If you're in the EJB tier for this whole process, I would certainly use them.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Will Hartung
  • 115,893
  • 19
  • 128
  • 203