Race condition could occur even when “check-and-act” action is not involved, for example in the following code ten requests would result in ten threads but the counter is not guaranteed to be 10 after that. First of all am I right in saying that?
private int numPageHits;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
//this method executes whenever the servlet is hit
//increment numPageHits
numPageHits++;
}
One solution could be to use synchronize block like:
synchronize(this) {
numPageHits++;
}
I was just wondering if there is another way of handling this situation?
Thanks
As pajton suggested, use
AtomicIntegerorAtomicLong,incrementAndGet()method would be even better.The code without
synchronizedis not only a subject of race condition, but also introduces thread visibility problem. Seevolatilekeyword.