Multi-Dispatch in the Java Virtual Machine TM What is (dynamic) multi-dispatch? Method selection based on the types of … all (or more than one) of the.

Slides:



Advertisements
Similar presentations
Overloading Having more than one method with the same name is known as overloading. Overloading is legal in Java as long as each version takes different.
Advertisements

Designing a Program & the Java Programming Language
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
1 Classes and Objects in Java Basics of Classes in Java.
1 Classes and Objects in Java Parameter Passing, Delegation, Visibility Control, and Object Cleanup.
A Programmer's Introduction to Java - from a S/370 user (c) IDMS/SQL News
8 March 2013Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Overriding CMPS Overriding Recall, a method in a child class overrides a method in the parent class, if it has the same name and type signature.
Object Initialization in X10 Yoav Zibin David Cunningham Igor Peshansky Vijay Saraswat IBM research in TJ Watson.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Recursive Factorial Demo pubic class Factorial {
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Programming Methodology (1). Implementing Methods main.
CPSC 441 TUTORIAL – JANUARY 16, 2012 TA: MARYAM ELAHI INTRODUCTION TO C.
Phil Campbell London South Bank University Java 1 First Steps.
Mohamed. M. Saad.  Java Virtual Machine Prototype based on Jikes RVM  Targets  Code profiling/visualization using execution flow  Utilize large number.
Loops –Do while Do While Reading for this Lecture, L&L, 5.7.
Picture It Very Basic Game Picture Pepper. Original Game import java.util.Scanner; public class Game { public static void main() { Scanner scan=new Scanner(System.in);
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Java Applets:. How Applets differ from application?: They do not use main method but init(), start() and paint() methods of the applet class They can.
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Hand Trace and Output for: int digit = 0; int number = 1423; do { digit = number % 10; System.out.println(digit); number = number / 10; } while (number.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Objects and Classes First Programming Concepts. 14/10/2004Lecture 1a: Introduction 2 Fundamental Concepts object class method parameter data type.
Overloading methods review When is the return statement required? What do the following method headers tell us? public static int max (int a, int b)
1 Programming Languages b Each type of CPU has its own specific machine language b But, writing programs in machine languages is cumbersome (too detailed)
Stacks and HeapsCS-502 Fall A Short Digression Stacks and Heaps CS-502, Operating Systems Fall 2007 (Slides include materials from Operating System.
Lecture From Chapter 6 & /8/10 1 Method of Classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Hudson Valley Community College CISS-110 – Programming & Logic I David Goldschmidt, Ph.D.
Java Dynamic Proxy Bibliography: reflection/proxy.html
JAVA Practical Creating our first program 2. Source code file 3. Class file 4. Understanding the different parts of our program 5. Escape characters.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Overview of Java CSCI 392 Day One. Running C code vs Java code C Source Code C Compiler Object File (machine code) Library Files Linker Executable File.
By Mr. Muhammad Pervez Akhtar
Chapter 6 Methods Chapter 6 - Methods.
CET 3640 Instructor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Programming in the Context of a Typical Computer Computer Studies Created by Rex Woollard.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
Methods.
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
Polymorphism 1. Reuse of code: every time a new sub-class is defined, programmers are reusing the code in a super-class. All non-private members of a.
Memory Management in Java Mr. Gerb Computer Science 4.
CSCE 343 – Programming Language Concepts Welcome!.
Introduction to java (class and object). Programming languages: –Easier to understand than CPU instructions –Needs to be translated for the CPU to understand.
What is a compiler? Compiler Source code (e.g. C++) Target code
Inheritance and Polymorphism
Type Systems Terms to learn about types: Related concepts: Type
ATS Application Programming: Java Programming
Object Oriented Programming
Subtyping Rules David Evans cs205: engineering software BlackBear
CSC 113: Computer programming II
Subprograms and Programmer Defined Data Type
Sampath Kumar S Assistant Professor, SECE
JAVA Constructors.
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Chapter 10: Method Overriding and method Overloading
Method of Classes Chapter 7, page 155 Lecture /4/6.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Method Overriding and method Overloading
Type Systems Terms to learn about types: Related concepts: Type
Subtype Substitution Principle
Corresponds with Chapter 5
Presentation transcript:

Multi-Dispatch in the Java Virtual Machine TM What is (dynamic) multi-dispatch? Method selection based on the types of … all (or more than one) of the arguments … at execution time (not compile time). Theatre t = new Theatre(); Orchestra o = new Orchestra(); Person duane = new Person(" Duane "); Person chris = new Student(" Chris "); System.out.println(duane + ": " + t.admission(duane) + " and " + o.admission(duane) + "." ); System.out.println(chris + ": " + t.admission(chris) + " and " + o.admission(chris) + "." ); Duane: pays $10 and pays $40. Chris: pays $10 and pays $40. Duane: pays $10 and pays $40. Chris: pays $5 and pays $25. class Person { /* … */ } class Student extends Person { /* … */ } class Theatre { String admission(Person p) {return "pays $10" ;} String admission(Student s) {return "pays $5" ; }} class Orchestra { String admission(Person p) {return "pays $40" ;} String admission(Student s) {return "pays $25" ;}} What does this code return? Given these definitions: Isn’t this method overloading? Statically, chris is a ‘Person’. Dynamically, chris is a ‘Student’. The Container Problem still applies; static multi-dispatch (method overloading) isn’t enough, nor are parametric types: Person lineUp[] = { new Student(" Chris "), new Person(" Paul "), new Person(" Duane "), new Student(" Steve "), new Person(" Wade ")}; for (int i=0; i<lineUp.length; i++) { System.out.println(lineUp[i] + ": " + t.admission(lineUp[i]) + " and " + o.admission(lineUp[i]) + "." ); } Method overloading requires the compiler to know the type of lineUp[i]. The compiler sees them all as type ‘Person’; the container obscures the dynamic type of ‘Student’ elements. The programmer cannot simply insert a cast to ‘Student’ – some elements are ‘Person’. Previously, how did people work around this problem? Type Numbering abstract class Venue { abstract String studentAdmission(); abstract String personAdmission(); String admission(Person p) { if (p instanceof Student) {return studentAdmission();} else if (p instanceof Person){return personAdmission();} }} class Theatre extends Venue { String personAdmission() {return "pays $10" ;} String studentAdmission() {return "pays $5" ; }} class Orchestra extends Venue { String personAdmission() {return "pays $40" ;} String studentAdmission() {return "pays $25" ;}} Difficulties:  overhead: second method invocation  maintainability: custom dispatch code  clarity: logic spread across all classes Visitor Pattern (Double Dispatch) abstract class Visitor { abstract String visitTheatre(Theatre t); abstract String visitOrchestra(Orchestra o); } class Person extends Visitor { String visitTheatre(Theatre t) {return "pays $10" ;} String visitOrchestra(Orchestra o){return "pays $40" ;}} class Student extends Person { String visitTheatre(Theatre t) {return "pays $5" ;} String visitOrchestra(Orchestra o){return "pays $25" ;}} abstract class Venue { abstract String admission(Visitor v); } class Theatre extends Venue { String admission(Visitor v){return v.visitTheatre(this); }} class Orchestra extends Venue { String admission(Visitor v) {return v.visitOrchestra(this);}} Type Testing class Person { static final int PERSON_TYPE = 0; protected int id = PERSON_TYPE; } class Student extends Person{ static final int STUDENT_TYPE = 1; Student() { this.id = STUDENT_TYPE }; } class Theatre { String admission(Person p) { switch (p.id) { case PERSON_TYPE: return "pays $10" ; case STUDENT_TYPE: return "pays $5" ; }} class Orchestra { String admission(Person p) { switch (p.id) { case PERSON_TYPE: return "pays $40" ; case STUDENT_TYPE: return "pays $25" ; }} Difficulties:  overhead: second method invocation  overhead: instanceof is costly  error-prone: always test subtypes first  Type Testing that trades extensibility and maintainability of OO for performance: replicated switch  second method invocation instanceof  manifest constants But, how common is this problem? Binary Operations Drag and Drop This occurs frequently enough that a solution (Visitor) was included in the original GOF design patterns; common situations include: Event Programming class AWTEvent { /* … */ } class MouseEvent extends AWTEvent { /* … */ } class KeyboardEvent extends AWTEvent { /* … */ } class FocusEvent extends AWTEvent { /* … */ } … class Component { void processEvent(AWTEvent e) { /* … */ } } class Window extends Component { /* … */ } class Button extends Component { /* … */ } class ScrollBar extends Component { /* … */ } class JComponent extends Component { /* … */ } … class Viewer { DropTargetListener vDropListener; …} class Printer {DropTargetListener pDropListener; …} class TextDocument implements Transferable {/* … */ } class Spreadsheet implements Transferable {/* … */ } class GraphicsImage implements Transferable {/* … */ } The heart of AWT (and Swing) is dispatching a queue of various kinds of events to a variety of GUI components. Drag and drop is the prototypical situation requiring dispatch on multiple arguments. The actions of the drop target depend on the kind of target and the kind of object transferred. Many operations, such as merges and comparisons, depend intimately on the types of their operands. class CustomerList { CustomerList merge(CustomerList c) { //O(nlogn) return this.sort().merge(c.sort()); } CustomerList merge(SortedCustomerList s) { //O(nlogn) return this.sort().merge(s); } } class SortedCustomerList extends CustomerList { CustomerList merge(CustomerList c) { //O(nlogn) return this.merge(c.sort()); } CustomerList merge(SortedCustomerList s) { //O(n) /* actually merge in linear time */ } } How does the JVM perform a multi-dispatch? Native multi-dispatch in the Java Virtual Machine At a method invocation, the JVM has the message selector the arguments on a stack the list of potential methods … Theatre t = new Theatre(); Orchestra o = new Orchestra(); Person duane = new Person(" Duane "); Person chris = new Student(" Chris "); System.out.println(duane + ": " + t.admission(duane) + " and " + o.admission(duane) + "." ); System.out.println(chris + ": " + t.admission(chris) + " and " + o.admission(chris) + "." ); Behavior admission Theatre, Person  String Theatre, Student  String Orchestra, Person  String Orchestra, Student  String [ ^"pays $10" ] [ ^"pays $5" ] [ ^"pays $25" ] [ ^"pays $40" ] … // bytecode before t.admission(chris) aload 1 // push t aload 2 // push chris invokevirtual #6 // method Theatre.admission(Person)String … // bytecode after t.admission(chris) Student chris Theatre t … byte code stackmethod dictionary … so the JVM can determine the types of the stacked arguments select another method that more closely matches the argument types What does the multi-dispatch version look like? class Person { /* … */ } class Student extends Person { /* … */ } class Theatre implements VirtualMultiDispatchable { String admission(Person p) {return "pays $10" ;} String admission(Student s) {return "pays $5" ; }} class Orchestra implements VirtualMultiDispatchable { String admission(Person p) {return "pays $40" ;} String admission(Student s) {return "pays $25" ;}} Without language extensions or custom dispatch code, the programmer can target multi-dispatch to only the classes that require this technique. Theatre t = new Theatre(); Orchestra o = new Orchestra(); Person duane = new Person(" Duane "); Person chris = new Student(" Chris "); System.out.println(duane + ": " + t.admission(duane) + " and " + o.admission(duane) + "." ); System.out.println(chris + ": " + t.admission(chris) + " and " + o.admission(chris) + "." ); Duane: pays $10 and pays $40. Chris: pays $5 and pays $25. Implement empty marker interface (like Cloneable ) signaling JVM to multi-dispatch this class How efficient is it? High-performance SRP+ multi-dispatcher operates faster than double- dispatching in the Java interpreter (tested on Sun classic VM for Linux): Multi-Dispatch AWT and Swing Advantages:  No second method invocation  No custom written dispatch code  No type tests  No type numbering  Extensible without changing existing libraries We modified Swing and AWT to use multi-dispatch:  changed 92 out of 846 classes  removed 123 custom-coded dispatcher methods  eliminated 171 decision points (if/else and switch/case statements)  reduced average decisions in each changed method from 3.8 to 2.0  replaced 4.74 million dispatches with 2.35 million multi-dispatches … with faster dispatch What are the benefits of this multi-dispatch approach? No language extensions or preprocessors:  maintains tool support: debuggers, profilers work on as-written code  Java source and binary compatible: we compile with the original javac  extend third-party components to use multi-dispatch without source  maintains reflection API – methods appear exactly as written Programmer-targeted multi-dispatch: use it only where needed  single dispatch has unchanged performance and semantics Full JVM support:  multi-dispatch instance and static methods (separately selectable)  multi-dispatch native and private methods, constructors, and super calls  add multi-dispatch to languages that emit.class files (Eiffel, Ada) Better performance than custom type-numbers without sacrificing OO Christopher DutchynPaul LuDuane SzafronSteve BromlingWade Holst Is this still OO?