Spotbugs is reporting a "Mutable servlet field" warning in this code (simplified test case):
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MutableFieldServlet extends HttpServlet
{
private String etag;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
synchronized (this)
{
if (etag == null)
etag = "\"" + System.currentTimeMillis() + "\"";
}
resp.addHeader("ETag", etag);
resp.getWriter().println("Hello world");
}
}
The description says: "A web server generally only creates one instance of servlet or JSP class (i.e., treats the class as a Singleton), and will have multiple threads invoke methods on that instance to service multiple simultaneous requests. Thus, having a mutable instance field generally creates race conditions."
However in this case I would say that there is no race condition as all writes to the field happen within a synchronized block. Is this a false positive?
Edit: This is just a simplified test case that can be used to reproduce the SpotBugs warning. The actual code obviously does not use a timestamp as an etag.