Tuesday, 14 May 2013

How are Java generics implemented under the hood?

Introduction


Today at lunch we had a chat about generics and their implementation in Java. Generics are available since Java 5. To stay byte code compatible between Java 1.4 and 5 generics are implemented by using type erasure. That means that at compile time all generic types are striped out and the resulting byte code only contains raw types like:

List a = ArrayList();
instead of
List<MyType> a = new ArrayList<MyType>();

This means that when we read elements of the list at runtime there needs be a cast added to check that both sides of the assignment have a compatible type:

MyType a = (MyType)list.get(0);
instead of
MyType a = list.get(0);

Java Class File Disassembler

To analyse how this cast is actually implemented in Java byte code one can use the Java Class File Disassembler. This command line tool ships with every Oracle JDK distribution and is called javap.

To inspect the byte code of a given class file use the command: javap -c <classfile>
For example:

javap -c org.henrikeichenhardt.javabytecode.Main

The output can get quite verbose and it makes sense to boil down the problem you want to look at to a few lines of code - just enough so you can create and compile you scenario.

Under the hood

For our scenario the Java code would look like this:

package org.henrikeichenhardt.javabytecode;

import java.util.ArrayList;
import java.util.List;

public class Main {
   public static void main(final String[] args) {
    final List<Main> list = new ArrayList<Main>();
    list.add(new Main());
    
    final Main value = list.get(0);
   }
}

We simply create an java.util.ArrayList with type of Main and add one element to this list. Then we retrieve this element again from the list. This few lines of code result in the following output of javap:

Compiled from "Main.java"
public class org.henrikeichenhardt.javabytecode.Main extends java.lang.Object{
public org.henrikeichenhardt.javabytecode.Main();
  Signature: ()V
  Code:
   0:   aload_0
   1:   invokespecial   #8; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Signature: ([Ljava/lang/String;)V
  Code:
   0:   new     #16; //class java/util/ArrayList
   3:   dup
   4:   invokespecial   #18; //Method java/util/ArrayList."<init>":()V
   7:   astore_1
   8:   aload_1
   9:   new     #1; //class org/henrikeichenhardt/javabytecode/Main
   12:  dup
   13:  invokespecial   #19; //Method "<init>":()V
   16:  invokeinterface #20,  2; //InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
   21:  pop
   22:  aload_1
   23:  iconst_0
   24:  invokeinterface #26,  2; //InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
   29:  checkcast       #1; //class org/henrikeichenhardt/javabytecode/Main
   32:  astore_2
   33:  return

}


The first block of information beginning with
public org.henrikeichenhardt.javabytecode.Main();
is the code to generate the (implicit) constructor of the Main object. We can ignore this for now. The second block of information is the byte code representing the code of the static main method
public static void main(java.lang.String[]);
On the first few lines the instances of the ArrayList is created and a reference is stored in on the stack. Then an instance of the Main object is created and added to the list. Now lets focus on reading an element from the list:

final Main value = list.get(0);

This resulting Java byte code looks like this:


   24:  invokeinterface #26,  2; //InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
   29:  checkcast       #1; //class org/henrikeichenhardt/javabytecode/Main
   32:  astore_2

Without going into to much detail here what basically happens is that invokeinterface calls the method get of our list and puts the result on top of the stack. Then the command checkcast is executed. It takes only one argument which is a reference to the type which needs to be checked (Main). This type is then compared with the top of the stack (where we previously put the result of list.get(0)).

How does checkcast work?


The documentation of the checkcast instruction reveals how this check is done:
  • If the stack reference is null nothing happens.
  • If the stack reference can be cast to the type provided nothing happens.
  • Otherwise a ClassCastException is thrown.
That means that checkcast is very similar to an instanceOf test. If the checkcast test is passed execution continues normally and the top of the stack is stored in a local variable.

So what the problem boils down to is how does checkcast know if it can cast a value to a type? The following is copied from [1]:

The following rules are used to determine whether an objectref that is not null can be cast to the resolved type: if S is the class of the object referred to by objectref and T is the resolved class, array, or interface type, checkcast determines whether objectref can be cast to type T as follows:
  • If S is an ordinary (nonarray) class, then:
    • If T is a class type, then S must be the same class as T, or S must be a subclass of T;
    • If T is an interface type, then S must implement interface T.
  • If S is an interface type, then:
    • If T is a class type, then T must be Object.
    • If T is an interface type, then T must be the same interface as S or a superinterface of S.
  • If S is a class representing the array type SC[], that is, an array of components of type SC, then:
    • If T is a class type, then T must be Object.
    • If T is an interface type, then T must be one of the interfaces implemented by arrays (JLS §4.10.3).
    • If T is an array type TC[], that is, an array of components of type TC, then one of the following must be true:
      • TC and SC are the same primitive type.
      • TC and SC are reference types, and type SC can be cast to TC by recursive application of these rules.
It is now up to the JVM implementation how efficient this checks are executed and if any profiling or heuristics are applied. In our example S is an ordinary class and T is a class type and both are the same which satisfies the first case above.

[1] Oracle checkcast

71 comments:

  1. Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

      Delete
    2. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important.Project Center in Chennai

      Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.

      Spring Training in Chennai

      The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in java programming your post help me a lot.Thanks for your informative article.java training in chennai | chennai's no.1 java training in chennai

    ReplyDelete
  3. perfect explanation about java programming .its very useful.thanks for your valuable information.java training in chennai | java training in velachery

    ReplyDelete
  4. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more .
    java training in chennai | Best java training in chennai | java training | java training in chennai with placement

    ReplyDelete
  5. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    full stack developer training in annanagar

    full stack developer training in tambaram

    full stack developer training in velachery

    ReplyDelete
  6. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.
    python training in rajajinagar
    Python training in btm
    Python training in marathahalli

    ReplyDelete
  7. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    Blueprism training in Chennai

    Blueprism training in Bangalore

    ReplyDelete
  8. Really very nice blog information for this one and more technical skills are improve,i like that kind of post.

    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  9. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.


    AWS Training in Bangalore | Amazon Web Services Training in bangalore , india

    AWS Training in pune | Amazon Web Services Training in Pune, india

    AWS Training in Chennai|Amazon Web Services Training in Chennai,India



    aws online training and certification | amazon web services online training ,india

    ReplyDelete
  10. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training

    ReplyDelete
  11. It is very good and very informative. There is a useful information in it.Thanks for posting...
    https://www.apponix.com/Java-Institute/Java-Training-Institute-in-Bangalore.html

    ReplyDelete
  12. Thanks for your informative article, Your post helped me to understand the future and career prospects & Keep on updating your blog with such awesome article.

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Hi,
    Good job & thank you very much for the new information, i learned something new. Very well written. It was sooo good to read and usefull to improve knowledge. Who want to learn this information most helpful. One who wanted to learn this technology IT employees will always suggest you take python training in pune. Because python course in pune is one of the best that one can do while choosing the course.

    ReplyDelete
  15. Thanks for your informative article.
    "Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional
    Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,
    Welding Inspector Course, Quality Management Course, #Safety officer course."
    Piping Design Course in India­
    Piping Design Course in Hyderabad
    Piping Design Course in Hyderabad
    QA / QC Course
    QA / QC Course in india
    QA / QC Course in Hyderabad
    Document Controller course
    Pressure Vessel Design Course
    Welding Inspector Course
    Quality Management Course
    Quality Management Course in india
    Safety officer course

    ReplyDelete
  16. Nice Information
    Yaaron Studios is one of the rapidly growing editing studios in Hyderabad. We are the best Video Editing services in Hyderabad. We provides best graphic works like logo reveals, corporate presentation Etc. And also we gives the best Outdoor/Indoor shoots and Ad Making services.

    Best video editing services in Hyderabad,ameerpet
    Best Graphic Designing services in Hyderabad,ameerpet­
    Best Ad Making services in Hyderabad,ameerpet­

    ReplyDelete
  17. Nice post. It is really interesting. Thanks for sharing the post!
    Buy AC Online | Smart LED TV
    Laptops for Sale | Best Inverter AC

    ReplyDelete
  18. Oracle offers varoious technolgoies pl sql, sql etc. oracle pl sql training is mainly for pl sql training

    ReplyDelete
  19. 1croreprojects offers the best 2019 robotics projects chennai for final year students.
    Visit :-
    https://meprojectschennai.co.in

    Phone : +91 97518 00789 / +91 77081 50152

    ReplyDelete

  20. 1croreprojects offers the best
    ieee embedded projects chennai
    for final year students

    ReplyDelete
  21. I must appreciate you for providing such a valuable content for us. This is one amazing piece of article. Helped a lot in increasing my knowledge.

    oracle training in bangalore

    ReplyDelete
  22. thank you sharing this blog, this information is useful for understanding the java for beginner.
    java training bangalore
    javascript training bangalore

    ReplyDelete
  23. Great blog !It is best institute.Top Training institute In Coimbatore
    http://trainingincoimbatore.in/selenium-training-in-coimbatore.html
    http://trainingincoimbatore.in/dot-net-training-in-coimbatore.html
    http://trainingincoimbatore.in/amazon-web-services-training-in-coimbatore.html
    http://trainingincoimbatore.in/python-training-in-coimbatore.html
    http://trainingincoimbatore.in/ccna-training-in-coimbatore.html
    http://trainingincoimbatore.in/ccnp-training-in-coimbatore.html

    ReplyDelete
  24. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care
    http://onlinejobsupport.net/job-support/workday-online-job-support/
    http://onlinejobsupport.net/job-support/hadoop-online-job-support/
    http://onlinejobsupport.net/job-support/reactjs-online-job-support/
    http://onlinejobsupport.net/job-support/salesforce-online-job-support/
    http://onlinejobsupport.net/job-support/angular-online-job-support/
    http://onlinejobsupport.net/job-support/rpa-online-job-support/
    http://onlinejobsupport.net/job-support/blueprism-online-job-support/

    ReplyDelete
  25. Great engaging information. Thank you for sharing. I found this post engaging and meaningful, which has added value to my understanding. Keep sharing good information. Thanks
    Full-Stack Developer
    App development
    Front End Developer

    ReplyDelete
  26. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
    AWS training in chennai | AWS training in annanagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ReplyDelete
  27. Very nice blogs!!! i have to learning for lot of information for this sites. oracle training in chennai

    ReplyDelete
  28. This information is impressive. I am inspired with your post. Thank you so much for your information its very useful and helpful to me keep updating and sharing.

    Data science training
    Data Analytics Training
    Devops training
    Selenium training
    AWS Training courses and certification

    ReplyDelete
  29. Thank you for your valuable content.very helpful for learners and professionals. if you are looking for Selenium Testing Training in Gurgaon then Join iClass Gyanseyu

    ReplyDelete
  30. Really wonderful blog! Thanks for taking your valuable time to share this with us. Keep us updated with more such blogs.
    AWS Training in Chennai
    AWS Online Training
    AWS Training in Coimbatore

    ReplyDelete
  31. Set your career goal towards Oracle for a wealthy future with Infycle. Infycle Technologies is the best Oracle training institute in Chennai that gives the most trusted and best Oracle Training in 100% hands-on training guided by professional tutors in the field. In addition to this, the mock interviews will be given to the candidates to face the interviews with full confidence. Apart from all, the candidates will be placed in the top MNC's with an excellent salary package. To get it all, call 7502633633 and make this happen for your happy life.Best Oracle Training Institute in Chennai

    ReplyDelete