Search code examples
javamultithreadingjakarta-eeejb

Using @Timeout in EJB instead of Thread.sleep()


I am hitting a webservice from my code twice. The first hit gives me a product_ID using which as a path parameter I make the second get call which gives me the response.

The problem is that the second(GET) call should be hit after 2 seconds from the first(POST) call. I am using EJB in my project and the simplest solution is using Thread.sleep(2000). But EJB does not recommend the programmer to manage threads on it's own.

In my research I have found a probable solution, but due to my lack of EJB skills I am not able to understand it much. could someone guide me to solve this issue.

The URL to the probable solution is: Using the EJB3 timer service instead of Thread.sleep()


Solution

  • In your method of the first call, you should create a programmatic single action timer with a 2 second delay after the first call.

    Timer timer = timerService.createSingleActionTimer(2000, new TimerConfig(product_ID, true));
    

    When a programmatic timer expires (goes off), the container calls the method annotated @Timeout in the bean’s implementation class. The @Timeout method contains the business logic that handles the timed event.

    @Timeout
    public void handleTimerEvent(Timer timer) {
       String productId = timer.getInfo();
       someMethodWithDoSecondCallLogic(productInfo)
    }
    

    refs: