A race condition is a special condition that may occur inside a critical section.
A critical section is a section of code that is executed by multiple threads and where the sequence of execution for the threads makes a difference in the result of the concurrent execution of the critical section.
More formally, the situation where two threads compete for the same resource, where the sequence in which the resource is accessed is significant, is called race conditions. A code section that leads to race conditions is called a critical section.
Race conditions can be avoided by proper thread synchronization in critical sections. Thread synchronization can be achieved
- using a synchronized block of Java code.
- Thread synchronization can also be achieved using other synchronization constructs like locks or
- atomic variables like java.util.concurrent.atomic.AtomicInteger
Critical Section Throughput
For smaller critical sections making the whole critical section a synchronized block may work. But, for larger critical sections it may be beneficial to break the critical section into smaller critical sections, to allow multiple threads to execute each a smaller critical section. This may decrease contention on the shared resource, and thus increase throughput of the total critical section.