0

I have a simple method to check if input string is valid xpath

private boolean isXpath(String value) {
    boolean isXpath = true;
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.compile(value);
    } catch (XPathExpressionException e) {
        isXpath = false;
    }
    return isXpath;
}

Can I be sure that JIT compiler won't remove code inside try block, because of it has no side effects? Or it has (possible exception)?

Atul Dwivedi
  • 1,452
  • 16
  • 29
Vasiliy Pispanen
  • 227
  • 1
  • 12
  • If you want to force the compiler _not_ to perform any optimisations, look at [this](http://stackoverflow.com/questions/5242405/how-to-make-sure-no-jvm-and-compiler-optimization-occurs) – byxor Sep 07 '16 at 12:32

1 Answers1

6

Dead Code Eliminatino is not just about side-effects, but also about using the result of computation. Since your method returns isXpath, which cannot be derived without executing the try block, it is impossible for the JIT compiler to eliminate it.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • I wouldn't say impossible: If the JIT inlines `XPathFactory.newInstance().newXPath()` and due to constant propagation and similar optimisations can deduce that the code either always throws an exception or never, it could then simplify the whole method to `return CONST`. In practice that's so exceedingly unlikely that it's reasonable to call that impossible I agree. – Voo Sep 07 '16 at 16:36
  • Only under the assumption that no string is a valid XPath or all of them are, and the compiler can prove that. Clearly not applicable here. – Marko Topolnik Sep 07 '16 at 16:38
  • 1
    Well, there _is_ this edge case of a call site that uses a string constant. Then it would be theoretically possible to effectively memoize the return value of the call. – Marko Topolnik Sep 07 '16 at 17:15
  • 1
    I was thinking along the lines of passing say null in there, which I'm assuming would throw a NRE. – Voo Sep 07 '16 at 17:27