Reputation: 41613
So, I'm using an API which is a little unfriendly in certain ways. Basically, this API creates a resource which can be fetched later. This resource may or may not still exist when we go to fetch it later.
To fetch the previously created resource, you have to use a result guid like so:
String resultKey = "12345";
PersistedResult r = mFactory.getPersistedResult(resultKey);
Now, the tricky thing here is that getPersistedResult
does NOT throw an exception when called with an invalid guid... PersistedResult
is a lazy loader and will only fail when one of its methods is called (causing the object to load itself).
So, to try and determine whether or not the resource is valid, I'm doing the following:
PersistedResult r = null;
if (!StringUtils.isEmpty(resultKey)) {
try {
r = mFactory.getPersistedResult(resultKey);
r.getResultCount(); // Triggers exception if result key was invalid.
} catch (Exception e) {
// handle exception
}
}
Is my call to getResultCount
at risk of being optimized out because I'm not using the value?
Calling any method on PersistedResult
goes to an external database, just in case that matters.
Upvotes: 3
Views: 833
Reputation: 74800
Optimizations at runtime (or compile time, same) are not allowed to give you different results than it would be when nothing is optimized (apart from runtime or memory savings). If here your exception is not thrown because of optimization, this is definitively another behavior, and thus would be a bug.
(Note than in multithreaded environments this is a bit relaxed when concerning the relations between different threads.)
Upvotes: 3
Reputation: 822
The compiler can't assume that getResultCount() has no side-effects -- therefore it can't remove the call.
Upvotes: 7
Reputation: 77762
No, why would it be? Either getResultCount
won't be inlined, in which case it's a black box and has to be executed because it can do anything, or it will get inlined, in which case the compiler can see that it could potentially throw an exception, and will perform that action.
The fact that it has a return value doesn't matter. If that was a factor, then any function of any complexity would be at risk of getting optimized out if the caller doesn't check its return value.
Upvotes: 3