Name: md23716 Date: 04/11/2000
Symptoms:
consider static methods TRUE() and FALSE() returning true and false
respectively, each with some visible side-effect.
If these are called with the lazy operators, && and ||, they work as
expected.
However, if the following is evaluated:
( TRUE() || FALSE() ) || true
the result is false, but no side-effects are seen. The method calls
have been optimised away, even though one of them should have been executed.
This can be demonstrated using the following program:
public class t {
static int i = 0;
static int j = 0;
public static boolean TRUE() {
i++;
return true;
}
public static boolean FALSE() {
i++;
return false;
}
public static void main( String[] args ) {
if( ( TRUE() || FALSE() ) || true ) {
System.out.println( "Returned true" );
}
else {
System.out.println( "Returned false" );
}
System.out.println( "i is " + i + ", j is " + j );
}
}
The javap output is:
Compiled from t.java
public synchronized class t extends java.lang.Object
/* ACC_SUPER bit set */
{
static int i;
static int j;
public static boolean TRUE();
public static boolean FALSE();
public static void main(java.lang.String[]);
public t();
}
Method boolean TRUE()
0 getstatic #13 <Field int i>
3 iconst_1
4 iadd
5 putstatic #13 <Field int i>
8 iconst_1
9 ireturn
Method boolean FALSE()
0 getstatic #13 <Field int i>
3 iconst_1
4 iadd
5 putstatic #13 <Field int i>
8 iconst_0
9 ireturn
Method void main(java.lang.String[])
0 getstatic #15 <Field java.io.PrintStream out>
3 ldc #2 <String "Returned true">
5 invokevirtual #16 <Method void println(java.lang.String)>
8 getstatic #15 <Field java.io.PrintStream out>
11 new #6 <Class java.lang.StringBuffer>
14 dup
15 ldc #3 <String "i is ">
17 invokespecial #10 <Method java.lang.StringBuffer(java.lang.String)>
20 getstatic #13 <Field int i>
23 invokevirtual #11 <Method java.lang.StringBuffer append(int)>
26 ldc #1 <String ", j is ">
28 invokevirtual #12 <Method java.lang.StringBuffer append(java.lang.String)>
31 getstatic #14 <Field int j>
34 invokevirtual #11 <Method java.lang.StringBuffer append(int)>
37 invokevirtual #17 <Method java.lang.String toString()>
40 invokevirtual #16 <Method void println(java.lang.String)>
43 return
Method t()
0 aload_0
1 invokespecial #9 <Method java.lang.Object()>
4 return
Note that the calls to TRUE() and FALSE() from main() have been
optimised out completely by javac, and there is no longer any
sign of them in the bytecode.
So the problem is in javac, not in the JVM.
(Review ID: 103537)
======================================================================
- duplicates
-
JDK-4053506 JLS violation: (a() || true) cannot be optimized if a() raises Exception
- Closed