If your servlets only read from the request, write to the response, and save information in local variables, you needn't worry about the interaction among these threads. Once any information is saved in nonlocal variables, however, you must be aware that each of these client threads has the ability to manipulate a servlet's nonlocal variables. (Java Servlet Programming, Jason Hunter)
we can deal with this problem in 4 methods:
1. in the declare, use " public synchronized void doGet(...,...)"
2.in the function, use " synchronized(this){ //do things about nonlocal variables} "
3.in the function, assign the value of nonlocal variable to a (temp) local variable, then after " synchronized(this){ //do things about nonlocal variables, and assign the value of nonlocal variable to a (temp) local variable} "
4. decide that we are willing to suffer the consequences of ignoring synchronization issues.
本文探讨了当Servlet处理多个客户端请求时如何确保线程安全。针对非局部变量可能引发的问题,提出了四种解决方法:使用synchronized关键字修饰doGet方法;在方法内部使用synchronized块;通过局部变量操作非局部变量;接受不进行同步带来的后果。
827

被折叠的 条评论
为什么被折叠?



