Junior — Middle
Can you provide an example of a situation where a race condition occurs in a multithreaded environment?
sobes.tech AI
Answer from AI
Race condition occurs when multiple threads access and modify shared data simultaneously without proper synchronization. For example, if two threads increment a shared counter at the same time without using synchronized or other locking mechanisms, the final value may be incorrect.
Example:
class Counter {
int count = 0;
void increment() {
count = count + 1; // non-atomic operation
}
}
// If two threads call increment() simultaneously, the final count may only increase by 1 instead of 2.