大家在servlet、action等中,都注意过同步吗?
比如说:下面的servlet,有两个成员变量:captchaService,session/**
* 提供验证码图片的Servlet
*/
public class JcaptchaServlet extends HttpServlet
{
public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";
private ImageCaptchaService captchaService;
private SessionProvider session;
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
byte[] captchaChallengeAsJpeg = null;
// the output stream to render the captcha image as jpeg into
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
String captchaId = session.getSessionId(request, response);
BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());
// Jimi.putImage("image/jpeg", challenge, jpegOutputStream);
ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
} catch (IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} catch (CaptchaServiceException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);
ServletOutputStream responseOutputStream = response.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
}
doGet方法中,使用了 captchaService,session 两个成员变量
一般来说,在方法中,调用成员变量,都要加上同步,才能保证线程安全。
请问,这里应该使用同步吗?(方法上加上synchronized,或使用同步代码块)
大家在这种情况下,用同步吗?
求讨论。
--------------------编程问答-------------------- servlet的实现是单例,多线程 你的考虑是正确的 .
可以参考ThreadLocal;
ThreadLocal是保证在同一个线程内共享,而不同线程的实例是不同的。如果想在不同线程内共享,那么直接用公共静态属性即可,如:public static int pagesize;
补充:Java , Java EE