From the course: Complete Guide to Parallel and Concurrent Programming with Java

Unlock this course with a free trial

Join today to access over 24,700 courses taught by industry experts.

Mutual exclusion

Mutual exclusion

- Anytime multiple threads are concurrently reading and writing a shared resource, it creates the potential for incorrect behavior like a data race. But we can defend against that by identifying and protecting critical sections of code. A critical section or critical region is part of a program that accesses a shared resource such as a data structure in memory or an external device. And it may not operate correctly if multiple threads concurrently access it. The critical section needs to be protected so that it only allows one thread or process to execute in it at a time. - Baron and I experienced a data race as we added garlic to our shared shopping list. Because incrementing a value is actually a three step process. Read the current value, modify it, and then write back the result. Those three steps are a critical section, and they need to execute as an uninterrupted action, so we don't accidentally override each other. - I have an idea. Give me your pencil. (pencil snapping) - Hey,…

Contents