public class VoteTest extends HttpServlet {
    VoteSystem voteSystem = new VoteSystem();
    ...
    doPost(...){
        ...
        voteSystem.vote(Integer.parseInt(request.getParameter("number")));
        ...
    }
}public class VoteSystem {
    public void vote(int id) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
con.setAutoCommit(false);
pstmt = con
.prepareStatement("update voteGUI set count=count+1 where ID=?;");
pstmt.setInt(1, id);
synchronized (this) {
pstmt.execute();
con.commit();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
    ....
}
这是一个投票,数据库是mysql,ID是选项,count是票数,请教各位,是否有必要设置synchronized避免投票并发问题,如果要设置,怎么设置才能提高性能,小弟感觉只是严重匮乏,求高手帮助,请教解决这个问题需要补充哪一方面的知识

解决方案 »

  1.   

    在尽量小的范围内设置synchronized就ok了,不会很严重的影响性能的。
      

  2.   

    不需要呢,局部变量不存在线程安全问题,呵呵。产生线程安全问题的一般是被多个线程共享的局部变量,比如,这样的东西:public class MyRunnable implements Runnable {    // 这个对象由于是外部传进来的,如果 Runnable 启动多个并且
        // 在 run 方法中使用了就会产生线程安全问题
        // 这里的 Object 
        private List<String> list;    public MyRunnable(List<String> list) {
            this.list = list;
        }    public void run() {
            // todo
        }    
    }