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?
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.
The developer needs to make sure they have a consistent view of any field which can be changed.
This might be a solution
Object mObject = this.mObject;
return mObject != null ? mObject.toString() : "null";
or
return String.valueOf(mObject);
or
return ""+mObject;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With