DigitalZebra
DigitalZebra

Reputation: 41613

Java dead code elimination... is this code at risk of being optimized out?

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

Answers (4)

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32014

No. Because optimize cannot change semantic of code.

Upvotes: 1

Paŭlo Ebermann
Paŭlo Ebermann

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

Vance Maverick
Vance Maverick

Reputation: 822

The compiler can't assume that getResultCount() has no side-effects -- therefore it can't remove the call.

Upvotes: 7

EboMike
EboMike

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

Related Questions