Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 553
Plinio.Santos Avatar asked Feb 17 '26 01:02

Plinio.Santos


2 Answers

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.

like image 141
Jon Skeet Avatar answered Feb 18 '26 14:02

Jon Skeet


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;
like image 23
Peter Lawrey Avatar answered Feb 18 '26 16:02

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!