From the course: Advanced Java: Threads and Concurrency

Unlock the full course today

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

Thread interference: Race condition

Thread interference: Race condition - Java Tutorial

From the course: Advanced Java: Threads and Concurrency

Thread interference: Race condition

- [Instructor] Threads execute in an arbitrary order decided by the operating system. This is like vehicles overtaking each other, so there isn't any guarantee on the timing or ordering of thread execution. The timing or the ordering of thread execution affects the correctness of the results produced by the code executed by them when those threads are accessing a shared piece of data, like an object in the heap. This is more visible when computations on shared variables are done using non-atomic operations like increment. For example, something like counter++, which is a non-atomic operation. This is known as a race condition. Let's try to visualize this. When Thread1 and Thread2 are sharing the counter variable, if Thread1 gets a chance to execute first, it reads the current value of the counter, which is zero and increments it to one. Now, remember, counter++ is not an atomic calculation operation. It involves three different operations: read, update, write, that might be happening…

Contents