Somewhere in html:
form action="SynchTest" method="POST" name="form1"
input name="SubmitBtn" type="submit" value="SUBMIT"
_______________
public class SynchTest extends HttpServlet {
Asynch a = new Asynch();
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String title = "SynchTest";
int y = 40;
if(a.getValue() > y) {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
out.print(ex.toString());
}
a.subtract(y);
}
String value = "Value is: "
+ String.valueOf(a.getValue());
String threadInfo = Thread.currentThread().getName();
value = value +"\n" + "Thread name is: " + threadInfo;
out.println(MyHTML_util.getHTML(title,value));
} finally {
out.close();
}
}
_____________________
public class Asynch {
private int x = 100;
public int subtract(int y){
x = x-y;
return x;
}
public int getValue(){
return x;
}
}
(3 requests from different tabs) produced following result:
Value is: 60
Thread name is: http-thread-pool-8080(4)
Value is: 20
Thread name is: http-thread-pool-8080(5)
Value is: -20
Thread name is: http-thread-pool-8080(1)
After one hour the result was updated (again 60):
Value is: 60
Thread name is: http-thread-pool-8080(4)
So I know JVM creates only one instance of servlet and a separated thread for each request.
No comments:
Post a Comment