Take this thread:
a = 3; b = 3;
And take this thread:
b = 5; a = 5;
They both access the same data from a Monitor.
If they both run concurrently (by using threads), what outcomes are possible?
Interference happens when two operations, running in different threads, but acting on the same data, interleave. This means that the two operations consist of multiple steps, and the sequences of steps overlap.
Thread Interference Error. When multiple threads share the same memory, there is a chance that two or more different threads performing different operations on the same data interleave with each other and create inconsistent data in the memory.
Thread interference in java is a condition which occurs when more than one threads, executing simultaneously, access same piece of data. When more than one threads have access to same data, it is possible that data may get corrupted or one may not get the desired output.
If the data we share is read-only data, there will be no problem, because the data read by one thread is unaffected by whether or not another thread is reading the same data. However, once data is shared between threads, and one or more threads start modifying the data, and that's the start of problems.
Because the threads' operations can be performed in any order, any combination of a=3,5 and b=3,5 are possible.
To clarify for future readers:
Thread-1: a=3 b=3
,
Thread-2: b=5 a=5
Operational orders possible:
I: Thread-1, Thread-1, Thread-2, Thread-2
II: Thread-1, Thread-2, Thread-1, Thread-2
III: Thread-1, Thread-2, Thread-2, Thread-1
IV: Thread-2, Thread-1, Thread-2, Thread-1
V: Thread-2, Thread-2, Thread-1, Thread-1
VI: Thread-2, Thread-1, Thread-1, Thread-2
Let us try each:
I: a=3, b=3, b=5, a=5 --> a=5, b=5
II: a=3, b=5, b=3, a=5 --> a=5, b=3
III: a=3, b=5, a=5, b=3 --> a=5, b=3
IV: b=5, a=3, a=5, b=3 --> a=5, b=3
V: b=5, a=5, a=3, b=3 --> a=3, b=3
VI: b=5, a=3, b=3, a=5 --> a=5, b=3
Note that there are four ways to come up with a=5,b=3
. Thus if you had a fair probability of each thread ordering, you would come up with that result ~67% of the time. However, you have no guarantees of such a probability; in fact, you can be almost certain that the OS is biased in some unknown manner. The lesson is, you should not try to rely on undefined behavior to do ANYTHING for you.
(I know that last part was a little beyond the scope of the question but I think it bears keeping in mind.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With