3

I use Servlet/EJB model. When the user requests for a statement report for his past transactions, it takes hours for the server to generate the report. So the response is not sent from the server till the request is processed.

For eg. Client requests report -> Servlet receives request -> Calls EJB to process it , EJB generates the report after hours -> sends response to servlet -> responds to Client.

But is it possible to respond to the user as soon as the request is received in the servlet. For eg.

Client requests report -> Servlet receives request -> Servlet responds 'Report will be available soon'

Servlet -> Calls EJB to process it , EJB generates the report after hours -> sends response to servlet ->responds to Client when client requests the report again.

That is , can I create a thread from Servlet and use that for calling the EJB, while the Servlet responds to the user stating that the request will be processed soon

Miljen Mikic
  • 14,765
  • 8
  • 58
  • 66
Shankar Rajan
  • 130
  • 2
  • 8

1 Answers1

3

Your scenario screams for the asynchronous communication. That is, you should rewrite your application to have three different methods:

  • first one receives a request, generates unique ID which is immediately returned to the client and invokes EJB to generate the report; its signature would be something like:

    public String generateReportRequest(Object requestParameter) { .. }

  • second one receives a unique ID and checks with EJB whether the report generation is done; its signature would be:

    public boolean isReportGenerated(String uniqueID) { .. }

  • third one actually returns the report, but it should be invoked only when the second one returned that the report is ready:

    public Object returnReport(String uniqueID) { .. }

Since we are dealing with three methods, I would not recommend mixing servlets and EJBs, but instead turning EJBs into Web services, if that's suitable (just annotate your stateless bean with @WebService annotation and adjust the client).

In case that you need to have Servlets for some reason, don't create a new thread - read this answer to see why it is highly discouraged in Java EE application server. Instead, you can use message-driven beans - just put the request on the message queue and return the answer to the client; MDB will process it asynchronously.

Third option is to check asynchronous method invocation in Java EE.

Community
  • 1
  • 1
Miljen Mikic
  • 14,765
  • 8
  • 58
  • 66