Invoking asynchronous method from servlet
Context:
I have done alot of reading, but only found this semi-relevant.
I have a servlet that calls a method from another Java class, while
passing session-sensitive data. It is running on the Tomcat server.
It looks something like this:
@WebServlet(urlPatterns = {"/MyServlet", "/"})
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException{
HttpSession session = request.getSession(true); //Start a session
String UserID = session.getId(); //Get a unique
user ID
MyClass class = new MyClass(); //Initialize my class
String shortID = class.newID(UserID); //Call a method
from class
System.out.println("Your short ID is: " + shortID); //Print the
result
}
}
And say the class that I'm calling looks like this:
public class MyClass {
public String newID(String UserID){
String shortID;
... //Method for shortening the UserID
return(shortID);
}
}
The method of course requires much more processing than shown in this
trivial example.
Question 1:
Now, my current understanding is that when n users call MyServlet
simultaneously, Tomcat creates n threads in doGet method. So when method
newID is called synchronously, Tomcat queues the threads and and allows
them to execute one after another. Is this correct?
Question 2:
The problem arises when I have a large number of users, as the n th user
will have to wait for newID method to be completed n-1 times, which might
take a while. Therefore I will want to call the newID method
asynchronously in order to run n threads in parallel, so to increase the
throughput.
How can I achieve this?
Would you recommend using reflections, or wrapping the newID method inside
a Runnable?
Does Tomcat take care of ExecutorService, or do I need to implement it too?
Any help will be much appreciated. Example code will be useful too!
No comments:
Post a Comment