title: Spring race conditions singleton service stateful or stateless
body: <p>I am a little concerned about race conditions using Spring.
  I know the differences between all kind of scopes (singleton, prototype, session and so on)</p>
  
  <p>I also know that:</p>
  
  <ul>
  <li>A service has singleton scope by default</li>
  <li>I won't have problems with race conditions as long as my bean is stateless</li>
  </ul>
  
  <p>Even though I am not 100 percent sure about this stateless thing. The sources of my research always just focus on shared instance variables when talking about statefulness, but race conditions can not only arise when accessing instance variables. 
  I created the following example to illustrate my problem:</p>
  
  <pre><code>@Service
  public class AppleService {
  
    @Autowired
    private AppleRepository appleRepository;
  
    @Override
    public void doSomethingWithAppleCategory(String appleCategory) {
      boolean existsAppleInCategory = existsAppleInCategory(appleCategory);
      if(existsAppleInCategory) {
          // do something
      }
      else {
          throw new RuntimeException("There is no apple in the category: " + appleCategory);
      }
    }
  
    private boolean existsAppleInCategory(String appleCategory) {
      Iterable&lt;Apple&gt; allApples = appleRepository.findAll();
      return allApples.stream().anyMatch(a -&gt; a.getAppleCategory().equals(appleCategory));
    } 
  }
  </code></pre>
  
  <p>You can assume that the service is used in a rest controller or something similar. From my understanding there can be a problem with race conditions when the method existsAppleInCategory is called. For example thread1 has its slot and writes "false" to the variable existsAppleInCategory. Then thread 2 has its slot overwriting existsAppleInCategory with "true". Afterwards thread 1 has another time slot. => thread 1 now "does something" instead of throwing a RuntimeException.</p>
  
  <p>Is my assumption correct? Do I have problems with race conditions in this scenario?
  If not why? Can you possibly recommend any sources writing about this topic in detail (online sources, books, ...)?</p>
  
  <p>Thank you in advance!</p>