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

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
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
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"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
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
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
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 

Recently uploaded (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
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
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"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
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
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
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 

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