Q:

Servlet thread safety: instance variables vs. request scope attributes

This is the sample code, illustrating the usage of instance variable and request attribute:
    @WebServlet(name = "Upload", urlPatterns = {"/upload"})
    @MultipartConfig()
    public class Upload extends HttpServlet {

    private String txt;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       try{
        String txt2 = (String) request.getAttribute("txt2");
        //txt and txt2 variables are available for processing.
         ..........
          } finally {
        txt = null;//Prepare variable for next request.
       }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            .....
        request.setAttribute("txt2", someValue);
        //vs
        txt = someValue;

    processRequest(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            .....
     processRequest(request, response);
      }
    }

Now I know that instance variables should be never declared in servlets, because the same servlet is shared between concurent requests. But what about request attributes? Is it safe to use them?

A:

Not sure what you mean by initializing variables. On a servlet you mean or where?
Depending on what you need to do, maybe there are APIs involved in which you don't have control about the contracts (since they are not your APIs).
For example, when requesting is being processed by a filter chain. Maybe one filter is interested on data being set by a filter executed previously in the chain. You don't have means to pass data on the filter chain contract. Request attribute might be an option. Playing with ThreadLocal might be another, but it has performance implications and is not always suitable.
Another example, maybe you forward one request from a servlet to another. Again, you will not have an option to play with whatever member variable you define.
Also, if you were thinking on adding member variables on a servlet, remember Servlets are not thread-safe. What would you do? synchronize request processing, only one request being processed per servlet?

