SlideShare a Scribd company logo
1 of 18
Primitives in Generics
current state
Ivan St. Ivanov
Important disclaimer
 This is work in progress
 Likely to change
 I am not an expert
 Based on the State of Specialization
document by Brian Goetz (see
resources)
 Same things apply to Value Types
The state of generics
 Only over reference types
 If you want List<int>:
List<Integer> intList = new ArrayList<>();
 Performance penalty:
Heade
r
Pointer
Pointer
Pointer
Pointer
Heade
r
int Heade
r
int Heade
r
int Heade
r
int
But why?
 Type erasure in generics
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T get() {
return value;
}
}
 At runtime T is erased to Object
 No common “Object” for primitive and
reference types
Why erasure at all?
 Use case:
◦ class C uses (or extends) class A
◦ class A is generified
 Source and binary compatibility
◦ If class C does not compile: source
incompatibility
◦ If class C should be recompiled to link:
binary incompatibility
 No flag day allowed!
Possible approach
 Project Valhalla
 Compromise #1: current rules for
generics should not be changed
 Compromise #2: use separate
approaches for representing different
types
 Compromise #3: subclass rules:
ArrayList<int> <: List<int> YES
List<int> <: List<Integer> NO
List<int> <: List<?> NO
List<int> <: List NO
Proposed syntax
 Introduce any type variable modifier
public class Box<any T> {
private T value;
public Box(T value) {
this.value = value;
}
public T get() {
return value;
}
}
 And then:
Box<int> intBox = new Box<>(42);
What about byte code?
ErasedBox (for reference types)
SpecialBox (for primitive types)
Side note: translations
 Heterogeneous translation
◦ Different runtime class for each different
parametric type
◦ Hard to achieve data parametricity (Box<?>)
◦ C++ templates
 Homogeneous translation
◦ Same runtime type for all different parametric
types
◦ Java achieved it for reference types
◦ C# for reference and structural types
◦ .NET byte code can range over both types,
Java - not
Representation in bytecode
 Erasure of reference types,
specialization for primitives
 Look again at SpecialBox usage site:
 Class name augmented with
specialization info
Restrictions for any T
 Cannot be converted or compared to
null
 Cannot be converted to Object or
Object[]
 Cannot be used as lock for
synchronization
 Cannot convert Foo<any T> to Foo<?>
or Foo
Available only for <any T>
 Support for new T[size]
 Use it where reference type is allowed
(instanceof)
 Foo<any T>.class
Generic methods
 Workaround for not allowing raw types
to be passed when <any T> is
expected
 Implementation:
◦ A version of the <any T> method should be
specialized
◦ Assumption: methods in a class are fixed
◦ invokedynamic is used
<any T> generic method
public class SpecializedMethod {
public <any T> T returnValue(T value) { return value; }
public static void main(String[] args) {
SpecializedMethod m = new SpecializedMethod();
m.returnValue(42);
}
}
 Bytecode at call site:
Migration challenges
 Wrong assumptions in some classes:
T[] array = (T[]) new Object();
 Problematic overloading
remove(int position);
remove(T element);
 Incompletely generified methods
remove(Object)
 There’s no null value for primitives
Possible approach: peeling
 Implement the backward compatibility method in
reference-specific layer
 Add new methods in generic layer
interface List<any T> {
void removeByValue(T element);
void removeByIndex(int pos);
layer<ref T> {
void remove(int pos);
void remove(T element);
default void removeByIndex(int pos) { remove(pos); }
default void removeByValue(T t) { remove(t); }
}
}
 The erased class will have all methods
 The specialized class will only have generic layer
methods
Time for experiments
 ArrayList or Optional class that is generic over
<any T>
 Write generic method over <any T> and pass:
reference type, primitive and raw type
 Specialized classes as method parameters,
return types of methods in erased generic or
non-generic classes
 Usage of static member variables and static
methods of specialized classes
 Inner classes combination (specialized in
specialized, specialized in erased, erased in
specialized, specialized in non-generic)
 Create new array of T inside specialized generic
class
 Call instanceof or .class
Resources
State of Specialization (by Brian Goetz)
http://cr.openjdk.java.net/~briangoetz/va
lhalla/specialization.html
Stewardship the Sobering Parts
https://www.youtube.com/watch?v=2y5
Pv4yN0b0
Source, binary and behavioral
compatibility
https://blogs.oracle.com/darcy/entry/kin
ds_of_compatibility

More Related Content

What's hot (17)

Core Java
Core JavaCore Java
Core Java
 
Implementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyImplementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in Dotty
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Templates
TemplatesTemplates
Templates
 
C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning Objects
 
Advanced PHP Simplified
Advanced PHP SimplifiedAdvanced PHP Simplified
Advanced PHP Simplified
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Generics
GenericsGenerics
Generics
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
C# basics
 C# basics C# basics
C# basics
 
03 oo with-c-sharp
03 oo with-c-sharp03 oo with-c-sharp
03 oo with-c-sharp
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Templates2
Templates2Templates2
Templates2
 
C++ Templates 2
C++ Templates 2C++ Templates 2
C++ Templates 2
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
Algorithmic Notations
Algorithmic NotationsAlgorithmic Notations
Algorithmic Notations
 

Similar to Primitives in Generics

Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language ComparisonRobert Bachmann
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 
Introduction to c sharp
Introduction to c sharpIntroduction to c sharp
Introduction to c sharpimmamir2
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and conceptsNicola Bonelli
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...Andrey Upadyshev
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Alexander Podkhalyuzin
 

Similar to Primitives in Generics (20)

Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
 
Java Generics
Java GenericsJava Generics
Java Generics
 
1204csharp
1204csharp1204csharp
1204csharp
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Introduction to c sharp
Introduction to c sharpIntroduction to c sharp
Introduction to c sharp
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Java generics
Java genericsJava generics
Java generics
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
core java
 core java core java
core java
 
Scala
ScalaScala
Scala
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Boost.Dispatch
Boost.DispatchBoost.Dispatch
Boost.Dispatch
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
[OLD VERSION, SEE DESCRIPTION FOR THE NEWER VERSION LINK] Hot С++: Universal ...
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)
 

Recently uploaded

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dashnarutouzumaki53779
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 

Recently uploaded (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dash
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 

Primitives in Generics

  • 1. Primitives in Generics current state Ivan St. Ivanov
  • 2. Important disclaimer  This is work in progress  Likely to change  I am not an expert  Based on the State of Specialization document by Brian Goetz (see resources)  Same things apply to Value Types
  • 3. The state of generics  Only over reference types  If you want List<int>: List<Integer> intList = new ArrayList<>();  Performance penalty: Heade r Pointer Pointer Pointer Pointer Heade r int Heade r int Heade r int Heade r int
  • 4. But why?  Type erasure in generics public class Box<T> { private T value; public Box(T value) { this.value = value; } public T get() { return value; } }  At runtime T is erased to Object  No common “Object” for primitive and reference types
  • 5. Why erasure at all?  Use case: ◦ class C uses (or extends) class A ◦ class A is generified  Source and binary compatibility ◦ If class C does not compile: source incompatibility ◦ If class C should be recompiled to link: binary incompatibility  No flag day allowed!
  • 6. Possible approach  Project Valhalla  Compromise #1: current rules for generics should not be changed  Compromise #2: use separate approaches for representing different types  Compromise #3: subclass rules: ArrayList<int> <: List<int> YES List<int> <: List<Integer> NO List<int> <: List<?> NO List<int> <: List NO
  • 7. Proposed syntax  Introduce any type variable modifier public class Box<any T> { private T value; public Box(T value) { this.value = value; } public T get() { return value; } }  And then: Box<int> intBox = new Box<>(42);
  • 8. What about byte code? ErasedBox (for reference types) SpecialBox (for primitive types)
  • 9. Side note: translations  Heterogeneous translation ◦ Different runtime class for each different parametric type ◦ Hard to achieve data parametricity (Box<?>) ◦ C++ templates  Homogeneous translation ◦ Same runtime type for all different parametric types ◦ Java achieved it for reference types ◦ C# for reference and structural types ◦ .NET byte code can range over both types, Java - not
  • 10. Representation in bytecode  Erasure of reference types, specialization for primitives  Look again at SpecialBox usage site:  Class name augmented with specialization info
  • 11. Restrictions for any T  Cannot be converted or compared to null  Cannot be converted to Object or Object[]  Cannot be used as lock for synchronization  Cannot convert Foo<any T> to Foo<?> or Foo
  • 12. Available only for <any T>  Support for new T[size]  Use it where reference type is allowed (instanceof)  Foo<any T>.class
  • 13. Generic methods  Workaround for not allowing raw types to be passed when <any T> is expected  Implementation: ◦ A version of the <any T> method should be specialized ◦ Assumption: methods in a class are fixed ◦ invokedynamic is used
  • 14. <any T> generic method public class SpecializedMethod { public <any T> T returnValue(T value) { return value; } public static void main(String[] args) { SpecializedMethod m = new SpecializedMethod(); m.returnValue(42); } }  Bytecode at call site:
  • 15. Migration challenges  Wrong assumptions in some classes: T[] array = (T[]) new Object();  Problematic overloading remove(int position); remove(T element);  Incompletely generified methods remove(Object)  There’s no null value for primitives
  • 16. Possible approach: peeling  Implement the backward compatibility method in reference-specific layer  Add new methods in generic layer interface List<any T> { void removeByValue(T element); void removeByIndex(int pos); layer<ref T> { void remove(int pos); void remove(T element); default void removeByIndex(int pos) { remove(pos); } default void removeByValue(T t) { remove(t); } } }  The erased class will have all methods  The specialized class will only have generic layer methods
  • 17. Time for experiments  ArrayList or Optional class that is generic over <any T>  Write generic method over <any T> and pass: reference type, primitive and raw type  Specialized classes as method parameters, return types of methods in erased generic or non-generic classes  Usage of static member variables and static methods of specialized classes  Inner classes combination (specialized in specialized, specialized in erased, erased in specialized, specialized in non-generic)  Create new array of T inside specialized generic class  Call instanceof or .class
  • 18. Resources State of Specialization (by Brian Goetz) http://cr.openjdk.java.net/~briangoetz/va lhalla/specialization.html Stewardship the Sobering Parts https://www.youtube.com/watch?v=2y5 Pv4yN0b0 Source, binary and behavioral compatibility https://blogs.oracle.com/darcy/entry/kin ds_of_compatibility