I am working on a web application using java servlet and here is my scenario:
servlet1: Has the application's interface and main logic
servlet2: Suplies values to servlet1 on ajax request from servlet1
Totally there are 250 values that servlet1 can request. But calculating these values in servlet2 takes time(As it involves making GET request to other servers to get values). So calculating these values on request makes the client to wait for a long time.
So is there a way to make servlet2 to start pre-calculating the values when servlet1 is first called(so it can quickly send the values on request)?
Any help on how this can be implemented?
P.S. database or filesystem cannot be used.
If the data that
servlet2needs to precalculate is not dependant onservlet1input and needs to be calculated only once, either calculate it eagerly inServletContextListener.contextInitialized()or inGenericServlet.init(). However it the computation takes some time, you’ll better move it to some background thread to avoid long application startup time (these methods block deployment until they are finished).Here is a simple example:
As you can see, when
servlet2starts, it initiates pre computation task in a separate thread. Then indoGet()you retrieve the result, possibly waiting for it, if it hasn’t finished yet.If the pre-computation is dependant on input in
servlet1(e.g. request parameters ofservlet1need to be used when calling external system), it’s much more challenging and interesting.I see at least two options:
start the
Futuretask inservlet1and retrieve that future (hopefully already finished) inservlet2. You need to pass it somehow between the servlets, e.g. by placing it inServletContextsend a message to jms queue from
servlet1. Message listener will process the request, precomputing the results and putting the result in some temporary, unique queue.servlet2can then later receive message from that queue (you’ll have to agree on some naming scheme somehow), or wait for it a little bit.