Consider a `@Service` bean with mutable state. How would changing the bean's scope from the default `singleton` to `prototype` affect a potential concurrency issue?
Java interview question for Advanced practice.
Answer
It resolves the race condition because a new instance of MyService is created for each injection, preventing state from being shared across different requests.
Explanation
Changing the scope to prototype means that a brand new instance of MyService is created every time it's needed (e.g., injected into another bean). This effectively resolves the concurrency issue because different threads will be operating on different instances of the service, each with its own private counter field. The shared mutable state, which was the source of the race condition in the singleton version, is eliminated.