title: Spring controllers - thread safety and storing resources
body: <p>I have a question about spring mvc and thread safety.</p>
  
  <p>We are developing web application that will be stored on tomcat. If I understand right, Tomcat creates thread per request and it has some thread pool. Now, dispatcher servlet is shared between requests and probably is thread safe. </p>
  
  <p>But when I create controller like this:</p>
  
  <pre><code>@Controller
  @RequestMapping("/manage")
  public class QuestionManagementController {
  </code></pre>
  
  <p>he has <code>Singleton</code> scope so the same controller is used by every request that comes from every user.</p>
  
  <p>I am wondering how this problem is usually solved: </p>
  
  <p>1: are controllers created with <code>Session</code> scope? (but I think that there also could be problems if one user quickly do some things that may lead to race conditions in the controller).</p>
  
  <p>2: controllers are scoped as <code>request</code></p>
  
  <p>3: creating stateless controllers that don't share any variables at class level, or have them in read only mode</p>
  
  <p>or maybe there is some better "best practice" that solves this kind of problem.</p>
  
  <p>I am asking this question, because now we have them as <code>Singleton</code> scoped, and there is a problem, that in most methods we are querying for user in the database , and we can't store this information in class level variable because of the scope. We could try to use some thread safe collection but later there could be other resources needing synchronized access.</p>