Concurrency In Multithreading In Java
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!
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;
- Thread 1 current=a; (T1 current = 0)
- Thread 2 current=a; (t2 current also = 0)
- Thread 1 prints current -> 0
- Thread 1 sets a=current+2 -> a=2;
- Thread 2 prints its own current which is still 0 set in step 2
- 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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM