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

965 Views Asked by At

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?

3

There are 3 best solutions below

3
On BEST ANSWER

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.

0
On

No, it's not thread safe, just make a local copy of mObject:

final Object local = mObject;
return (local != null ? local.toString() : "null"); 
0
On

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;