Ad

Concurrency In Multithreading In Java

- 1 answer

I was giving mock test for ocjp 6 exam and encountered the following question on Concurrent access:

public class Cruiser {
   private int a = 0;

    public void foo() {
        Runnable r = new LittleCruiser();
        new Thread(r).start();
        new Thread(r).start();
    }

    public static void main(String arg[]) {
        Cruiser c = new Cruiser();
        c.foo();
    }

public class LittleCruiser implements Runnable {
    public void run() {
            int current = 0;
            for (int i = 0; i < 4; i++) {
                current = a;
                System.out.print(current + ", ");
                a = current + 2;
            }
    }
}

What are the possible outputs ?

options:

A) 0, 2, 4, 0, 2, 4, 6, 6,

B) 0, 2, 4, 6, 8, 10, 12, 14,

C) 0, 2, 4, 6, 8, 10, 2, 4,

D) 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,

E) 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,

Answers are A and B.

My doubt is, how can option A be a possible output? I mean if first thread enter it's run method, it will change the value of a , and if in between second thread comes it will get the changed value of a,so how come numbers are repeated ? please explain this problem , thanks in advance!

Ad

Answer

IF there were no racing conditions the answer would be always B) because you increment the same variable. But this is not the case because in this code:

 current = a;
 System.out.print(current + ", ");
 a= current + 2;

You set current=a (which has some value), use it for printing but during that time another thread may have modified a. And then when you set a=current+2 you override that other threads change.

For example if the steps are: Initially a=0;

  1. Thread 1 current=a; (T1 current = 0)
  2. Thread 2 current=a; (t2 current also = 0)
  3. Thread 1 prints current -> 0
  4. Thread 1 sets a=current+2 -> a=2;
  5. Thread 2 prints its own current which is still 0 set in step 2
  6. Thread 2 sets a=current+2 -> a=2 basically overriding step 4 which occurred in the other thread

So you can get other possible answers too like:

0, 0, 2, 4, 6, 2, 4, 6,

0, 2, 4, 6, 0, 2, 4, 6,

0, 2, 4, 0, 2, 4, 6, 6, etc.

It depends on the way the threads are executed and what has happened between when we set current to something and then set a back to current+2

Ad
source: stackoverflow.com
Ad