Search code examples
javamultithreadingthread-safetyrace-conditionconditional-expressions

In Java, is a conditional expression a thread safe operation?


I'm wondering if a conditional expression is a thread safe operation in Java.
E.g.:

return (mObject != null ? mObject.toString() : "null");  

So, my question is: If two threads can change mObject, is this code thread safe, or does the developer need to handle any race conditions?


Solution

  • No, that's absolutely not thread-safe. You could definitely get a NullPointerException here. It's easy to fix, of course:

    Object tmp = mObject;
    return tmp != null ? tmp.toString() : "null";
    

    Or, even more easily in this particular case:

    return String.valueOf(mObject);
    

    EDIT: As noted in comments, if you've really got two threads racing to update a value with no synchronization, that's probably a sign of bigger problems... but I only tried to answer the question you specifically asked.