Is there any way to stop new client requests to s开发者_如何学JAVAervlet until old client request finishes execution in servlet? I do not want to use the synchronized
keyword, instead I would like to recognize each request thread in servlet. How can I achieve this?
At first sight, I would guess it should be possible to store a bool in the Context. Any arriving request checks the context-bool (let's name it "bBusy"). The first arriving request sets it and resets it when it has been handled. The second arriving one checks : If first one is still being handled, it will be recognized and then it's up to your phantasy what to happen... :)
I hope that is what you were thinking of?
EDIT: It has to be the correct context. My Servlet-times are somewhat long ago ... I guess ApplicationContext? - Not sure about that but you should be able to find it out by yourself.
Use the synchronized keyword in your servlet or in a filter. In the servlet methods you can write:
synchronized(this) { //code handling the request that will be executed //by only one thread/request at a time }
You can use an object that will provide the synchronization for you (depending on your needs) - see java.util.concurrent
You can try to use an algorithm for thread synchronization without using the primitives. (CS classes usually tell such algorithms)
You can try to configure your server to execute the requests sequentially. See http://tomcat.apache.org/tomcat-6.0-doc/config/executor.html
Keeping a AtomicBoolean/volatile in the servletcontext in a synchronized block can achieve the effect. Another way is to use the SingleThreadModel interface ( deprecated) but it still does the Job.
I am still wondering why do you want to do this.
You can use assert in the web application code (servlets etc). But make sure the web/app server is started with the -ea or corresponding arguments that controls the assertions.
精彩评论