Plinio.Santos
Plinio.Santos

Reputation: 1759

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?

Upvotes: 3

Views: 988

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502696

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.

Upvotes: 7

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340923

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

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

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533720

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;

Upvotes: 2

Related Questions