Note that there are some explanatory texts on larger screens.

plurals
  1. POIs the != check thread safe?
    primarykey
    data
    text
    <p>I know that compound operations such as <code>i++</code> are not thread safe as they involve <em>multiple</em> operations. </p> <p>But is checking the reference with itself a thread safe operation?</p> <pre><code>a != a //is this thread-safe </code></pre> <p>I tried to program this and use multiple threads but it didn't fail. I guess I could not simulate race on my machine.</p> <h2>EDIT:</h2> <pre><code>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(); } } </code></pre> <p>This is the program that I am using to test the thread-safety.</p> <h2>Weird behavior</h2> <p>As my program starts between some iterations I get the output flag value, which means that the reference <code>!=</code> check fails on the same reference. BUT after some iterations the output becomes constant value <code>false</code> and then executing the program for a long long time does not generate a single <code>true</code> output.</p> <p>As the output suggests after some n (not fixed) iterations the output seems to be constant value and does not change. </p> <p><strong>Output:</strong></p> <p>For some iterations:</p> <pre><code>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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload