Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for Thread 2 to print “x=0”?

Tags:

java

Is it possible for Thread 2 to print “x=0”?

int x = 0;
boolean bExit = false;

Thread 1 (not synchronized)
x = 1; 
bExit = true;

Thread 2 (not synchronized)
if (bExit == true) 
System.out.println("x=" + x);
like image 853
Dhaval Avatar asked Sep 01 '15 05:09

Dhaval


People also ask

Does thread X increment the shared number before printing?

So it is possible that thread x increments the shared number but before printing the time slice is passed to the next thread y which now reads the shared number and prints it after incrementing (assuming that thread y got more time than thread x to increament and print the shared number) . Show activity on this post.

Is it possible to print numbers alternately from two threads?

This answer is generic i.e. not only to print numbers alternately from 2 threads but to execute 2 threads alternately.

Is it possible to print a fine thread?

While it is possible that with the right combination of settings (resolution, nozzle size, etc) you can print a fine thread, it is simply not worth the hassle because there are so many good alternatives. Our preferred methodology is to incorporate a heat set insert into your design, which is added after your part has been 3D printed.

Can You 3D print a functional thread?

For very large and coarse threads, it is possible to 3D print a functional thread. This technique should be reserved for applications were a custom thread is required due to the part design...imagine a custom thread on a water bottle cap, or a thread to attach a tool to the end of a painter's stick. Wait, what about 3D printing Hardware?


Video Answer


2 Answers

Is it possible for Thread 2 to print “x=0”?

Yes if instructions are reordered by the JIT compiler as:

Thread1:

bExit=true
x=1

Thread2:

 if (bExit == true) System.out.println("x=" + x); //prints 0

When you use synchronized block (or other related constructs) the instrcutions are not reordered by the compiler.

like image 79
akhil_mittal Avatar answered Sep 19 '22 12:09

akhil_mittal


Answer : Yes, It's possible that thread T2 may print x=0.Why? because without any instruction to compiler e.g. synchronized or volatile, bExit=true might come before x=1 in compiler reordering. Also x=1 might not become visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it? When I asked this question to couple of programmers they answer differently, one suggest to make both thread synchronized on a common mutex, another one said make both variable volatile. Both are correct, as it will prevent reordering and guarantee visibility. But best answer is you just need to make bExit as volatile, then Thread 2 can only print “x=1”. x does not need to be volatile because x cannot be reordered to come after bExit=true when bExit is volatile.

like image 45
Dhaval Avatar answered Sep 19 '22 12:09

Dhaval