0

EJB Spec says you shouldn't manage threads. I have seen Bean code that sends remote requests and loops with a Thread.sleep waiting for a response to reduce CPU usage. From what I understand this breaks spec. Does simply calling the logic from a separate POJO or library that is instantiated then referenced in the EJB's method fix this? Does simply removing Thread.sleep fix the issue at the cost of additional CPU consumption? How should external synchronous requests be coded in EJBs?

runtim23
  • 38
  • 5

1 Answers1

0

That depends on the business case. EJB spec provides plenty of resources for async/sync processing without boilerplate code using Thread, Runnable or any other mechanism.

To execute a piece or code asynchronously (that is, the caller won't wait for the response, but carry on), use @Asynchronous, and Future<T> if you want to listen for responses afterwords.

A synchronous call, as you called, is a call that waits for the response, so "How should external synchronous requests be coded in EJBs" is something that doesn't need any kind of asynchronous/background execution. You just make the call and the code itself wait for the response (otherwise it would be asynchronous), being the tipical case a Web Service (either REST or SOAP).

Web Services calls can actually be synchronous or asynchronous, that depends on the business case, but they are usualy synchronous, you make the call and receive a response with the data. In cases of business logic that takes a while to execute, the Web Service receives the resquest and may launch the business logic asynchronously (with an @Asynchronous for instance) and respond immediately with a plain HTTP 202 - Accepted, which basically means "Hey! The request you just sent me is gonna take a while, so I'll do it in the backround".

In that case, may be you have another web service that you need to check to see how that long lasting process is going. That is the only case I can think of in which someone will want that Thread.sleep(...) in a loop, checking the Web Service until it tells you that the process have finished.

Luckily, EJB also provides a solution for that business case:

  1. You can use @Schedule methods in case you need to check/do something indefenately, in specific intervals: something to do every day at 02:00, or every first day of month, or even every 2 seconds.
  2. Or TimerService and @Timeout, in case you want to programatically schedule a single task. This last fits better in the business case we are talking.

So you call the TimerService with the timespan you want to wait for the next check. When time comes the @Timeout method is fired, in which you can check whatever you need, and shcedule another execution in case you need it, even with a new timespan.

gmanjon
  • 1,483
  • 1
  • 12
  • 16