liveBook · Manning

Race condition

As explained in Spring Start Here, Second Edition

A race condition is an incorrect or nondeterministic result caused by concurrent operations accessing shared state without adequate coordination.

A race condition occurs when multiple threads change shared state without adequate coordination, causing unexpected results or errors. It can arise when a Spring singleton bean holds mutable data that concurrent requests share. section 5.1.1

A shared comment processor

If concurrent calls use one mutable CommentProcessor, one thread may overwrite another’s comment, leaving it unclear which comment was processed. A prototype bean can provide a new processor for each call, but retrieve it inside the method; injecting it once into a singleton still reuses that instance. section 5.2.1

Figure 5.5 When multiple threads access a singleton bean, they access the same instance. If these threads try to change the instance simultaneously, they run into race conditions. The race condition causes unexpected results or execution exceptions if the bean is not designed for concurrency.

See how simultaneous changes to one singleton instance can produce unexpected results or execution exceptions. section 5.1.1

How Spring Start Here, Second Edition covers it

How deep it goes
Defines the failure, illustrates it with shared bean state, and discusses synchronization and prototype scope as design responses.
Examples
Uses concurrent threads changing a singleton instance and a mutable CommentProcessor handling comments.
What it assumes
Assumes familiarity with Spring beans and multiple threads, while defining race conditions directly.
What you can do after
Apply Spring prototype scope by retrieving a fresh CommentProcessor inside each service method call.
How it connects
Connects race conditions to singleton beans, prototype scope, and thread synchronization.

Also explained in

Compare how 25 books explain race condition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.