Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences in java bytecode produced by Oracle's and Eclipse's compilers

Our project does some Java bytecode instrumentation. And we stumbled upon some strange behavior. Suppose the following code snippet:

  public void a() {
    new Integer(2);
  }

Oracle's javac compiles the above into the following bytecode:

   0:   new #2; //class java/lang/Integer
   3:   dup
   4:   iconst_2
   5:   invokespecial   #3; //Method java/lang/Integer."<init>":(I)V
   8:   pop
   9:   return

and Eclipse's compiler into:

   0:   new #15; //class java/lang/Integer
   3:   iconst_2
   4:   invokespecial   #17; //Method java/lang/Integer."<init>":(I)V
   7:   return

As you can see, Oracle compiler produces "dup" after "new", whereas Eclipse doesn't. Which is totally correct in this use case, as newly created Integer instance is not used at all, so no "dup" is required.

My questions are:

  1. Is there some overview of differences between different compilers? An article/blog post?
  2. Can I safely conclude, that if there is no "dup" between "new" and "invokespecial" then object is not used after initialization?
like image 293
Nikem Avatar asked Feb 09 '12 08:02

Nikem


2 Answers

Passing this reference will break this pattern a bit

  public class Bump {

    Test t;

    public Bump() {
        new Test(this);
    }
    public void setT(Test t) {
        this.t = t;
    }
  }

And then one could use this for storing the result back :)

  public class Test {

    Bump b;

    public Test(Bump b) {
        this.b = b;
        b.setT(this);
    }
  }

Have fun :)

like image 195
Anton Arhipov Avatar answered Nov 10 '22 00:11

Anton Arhipov


  1. Can I safely conclude, that if there is no "dup" between "new" and "invokespecial" then object is not used after initialization?

I'm not sure what you mean exactly, but a reference to the created object might be stored somewhere by the constructor. Therefore the calling method might not use the object after initialization but the object might still be reachable and might be not garbage collectable therefore.

like image 32
A.H. Avatar answered Nov 10 '22 00:11

A.H.