Servlet sau đếm số lượt truy cập. Khi chạy tải cao, con số cuối cùng thường thấp hơn số request thật. Vì sao?
@WebServlet("/visit")
public class VisitServlet extends HttpServlet {
private int count = 0;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
count++;
resp.getWriter().print("Visits: " + count);
}
}
Xem đáp án và giải thích
Servlet là singleton theo khai báo và được gọi đồng thời từ nhiều thread của thread pool, nên field là trạng thái dùng chung. count++ không atomic dẫn tới race condition. Hãy dùng AtomicInteger/LongAdder, hoặc tốt hơn là đừng giữ trạng thái thay đổi trong servlet.