Java – multithreaded gae servlet to handle concurrent users

I want to multithread my gae servlet so that the same servlet on the same instance can process up to 10 concurrent requests from different users at the same time (on the front-end instance, I believe the maximum # thread is 10)

public class MyServlet implements HttpServlet {
    private Executor executor;

    @Override
    public void doGet(HttpServletRequest request,HttpServletResponse response) {
        if(executor == null) {
            ThreadFactory threadFactory = ThreadManager.currentRequestFactory();
            executor = Executors.newCachedThreadPoolthreadFactory);
        }

        MyResult result = executor.submit(new MyTask(request));

        writeResponseAndReturn(response,result);
    }
}

So basically, when gae is started, an executor will be created and saved when the servlet request is obtained for the first time Each new servlet request then uses the executor to generate a new thread Obviously, everything in mytask must be thread safe

What I care about is whether it can really do what I want That is, does this code create a non blocking servlet that can handle multiple requests from multiple users at the same time? If not, why do I need to do something to solve it? And, in general, what can gae masters find wrong? Thank you in advance

Solution

I don't think your code works

The doget method is running in a thread managed by the servlet container When a request enters, a servlet thread is occupied and will not be released until the doget method returns In your code, the executor Submit will return a future object In order to get the actual results, you need to call the get method on the future object and will prevent mytask from completing its task Only after that can the doget method return and a new request be started

I'm not familiar with gae, but according to their docs, you can declare servlets thread safe, and then the container will concurrently allocate multiple requests to each web server:

<!-- in appengine-web.xml -->
<threadsafe>true</threadsafe>
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>