Search code examples
jakarta-eeejb

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.


Solution

  • 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.