user201891
user201891

Reputation:

How does javax.ejb.TimerService know which bean to call?

How does javax.ejb.TimerService (Glassfish 3.1.2.2) know which bean to execute?

In the Java EE 6 tutorial we learn that we can define timer callbacks in an enterprise bean:

@Timeout
public void timeout(Timer timer) {
    System.out.println("TimerBean: timeout occurred");
}

Then we can schedule programmatic timers like this:

@Resource
TimerService timerService;
...
// Sets a programmatic timer that will expire in 1 minute (6,000 milliseconds):
long duration = 6000;
Timer timer = timerService.createSingleActionTimer(duration, new TimerConfig());

How does the TimeService know which bean to call? There can only be one annotated method in the bean, but how does it know which bean to call? this is not a parameter of createSingleActionTimer.

Upvotes: 4

Views: 1772

Answers (2)

Steve C
Steve C

Reputation: 19445

According to §13.2 of the EJB Specification:

Timers can be created for stateless session beans, singleton session beans, message-driven beans[88]. Timers cannot be created for stateful session beans[89].

The answer to your question for singleton session beans is self evident.

For stateless session beans, it makes no difference which bean instance is invoked as they have no state. The same applies to message driven beans.

Upvotes: 0

Brett Kail
Brett Kail

Reputation: 33946

It's implementation-defined, but there are at least two plausible implementation strategies:

  1. When the EJB container injects the TimerService into a bean instance, the TimerService could be bound to that EJB component, so when the timer needs to fire, it knows how to locate an instance and invoke the timeout method.
  2. When an EJB invokes a method, it could push metadata about the current EJB component and method onto a ThreadLocal, and when methods are invoked on the TimerService, it locates the current EJB component and creates timers based on that.

Upvotes: 1

Related Questions