dcnh35 dcnh35 - 1 month ago 8
Java Question

My java code's ouput is not as expected?

The following is my java code.

public class TestVolatile {

static class Test {
int a = 0;
int b = 0;
}

public static void main(String[] args) {

for(int i=0;i<10000;i++) {
final Test test = new Test();
new Thread(new Runnable() {
@Override
public void run() {
test.a = 1; //test.a assignment before test.b assignment
test.b = 1;
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("a="+test.a+",b="+test.b);
}
}).start();
}
}
}


I just want to find out all possible output with
java com.company.test_volatile.TestVolatile | sort -u
. But there are only three results without
a=1, b=0
.


a=0, b=0

a=0, b=1

a=1, b=1


No matter how many times I run the code, always get the same result. So what's the reason of no output
a=1, b=0
? Does the synchronization of
println
do with it?

Answer

I had to bruteforce it. There might have been a better way. I got an output with a=1, b=0.

$ for i in {1..1000}; do java TestVolatile | grep 'a=1,b=0'; done                                                                                                   
a=1,b=0
a=1,b=0
a=1,b=0
a=1,b=0
a=1,b=0

Its still going on. I'll update if I get more

Update: I got 5 matches from running 1000 * 1000 times. So the probability of this output is extremely low. As to why is it so, I guess its machine dependent.

Comments