title: Spring MVC - race conditions?
body: <p>Suppose I have the following Spring MVC controller</p>
  
  <pre><code>@RestController
  @RequestMapping("/books")
  public class BooksController {
  
    @Autowired    
    private final BooksRepository booksRepository;
  
    @RequestMapping(value="/search", method=RequestMethod.POST, consumes="application/json")
    public Collection&lt;Book&gt; doSearch(@RequestBody final SearchCriteria criteria) {
      return booksRepository.find(criteria);
    }
  }
  </code></pre>
  
  <p>and the following repository</p>
  
  <pre><code>@Service
  public class BooksRepository {
  
    @Autowired
    private final JdbcTemplate jdbcTemplate;
  
    @Autowired
    private final SearchQueryBuilder searchQueryBuilder;
  
    public Collection&lt;BookLite&gt; find(final SearchCriteria criteria) {
  
      // TODO: will this cause race conditions?
      searchQueryBuilder.clear().addKeywords(criteria.getKeywords());
  
      final String query = searchQueryBuilder.buildQuery();
      final Object[] params = searchQueryBuilder.buildParams();
  
      return jdbcTemplate.query(query, params, new BookExtractor());
    }
  }
  </code></pre>
  
  <p>with the following <code>SearchQueryBuilder</code> implementation</p>
  
  <pre><code>@Component
  public class SearchQueryBuilder {
  
    private final List&lt;String&gt; keywords = new LinkedList&lt;String&gt;();
  
    public SearchQueryBuilder clear() {
      keywords.clear();
      return this;
    }
  
    public SearchQueryBuilder addKeywords(final List&lt;String&gt; keywords) {
      for (String keyword : keywords) {
          add(keyword);
      }
      return this;
    }
  
    private SearchQueryBuilder add(final String keyword) {
      keywords.add(keyword);
      return this;
    }
  
    public String buildQuery() {
      ...
    }
  
    public Object[] buildParams() {
      ...
    }
  }
  </code></pre>
  
  <p>My concerns are the following. Since the SearchQueryBuilder class is not thread safe, injecting it this way will probably cause race conditions. What is a good way to handle this? Is it enough (and a good practice) to change the bean scope to e.g. request?</p>