Rhys Rhys - 2 months ago 5
Java Question

Threads interleaving - what possible results could be outputted

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?

Answer

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.)

Comments