I know that compound operations such as i++
are not thread safe as they involve multiple operations.
But is checking the reference with itself a thread safe operation?
a != a //is this thread-safe
I tried to program this and use multiple threads but it didn't fail. I guess I could not simulate race on my machine.
EDIT:
public class TestThreadSafety {
private Object a = new Object();
public static void main(String[] args) {
final TestThreadSafety instance = new TestThreadSafety();
Thread testingReferenceThread = new Thread(new Runnable() {
@Override
public void run() {
long countOfIterations = 0L;
while(true){
boolean flag = instance.a != instance.a;
if(flag)
System.out.println(countOfIterations + ":" + flag);
countOfIterations++;
}
}
});
Thread updatingReferenceThread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
instance.a = new Object();
}
}
});
testingReferenceThread.start();
updatingReferenceThread.start();
}
}
This is the program that I am using to test the thread-safety.
Weird behavior
As my program starts between some iterations I get the output flag value, which means that the reference !=
check fails on the same reference. BUT after some iterations the output becomes constant value false
and then executing the program for a long long time does not generate a single true
output.
As the output suggests after some n (not fixed) iterations the output seems to be constant value and does not change.
Output:
For some iterations:
1494:true
1495:true
1496:true
19970:true
19972:true
19974:true
//after this there is not a single instance when the condition becomes true
1234:true
never smash each other). A race test needs a tighter inner loop. Print a summary at the end (as someone did below with a unit test framework). – Ben Jackson