SlideShare a Scribd company logo
Back to the future: 
Evolution of the Java Type System 
www.luxoft.com
Agenda 
 History: Java 5 Type System 
 Generalized Target-Type Inference 
 Annotated Types 
 Checker Framework 
 Project Valhalla 
www.luxoft.com
Java 5 Type System 
 Parametric polymorphism 
public class Sample<T> { 
 Bounded wildcards 
 Intersection types 
 Type erasure 
www.luxoft.com 
private T data; 
public T getData() { ... } 
} 
Collection<? extends Serializable> 
public class Box<T extends Comparable & Clonable> { ...
Java 8 Type System 
 JEP 101: Generalized Target-Type Inference 
- Add support for method type-parameter inference in method context 
- Add support for method type-parameter inference in chained calls 
 JSR 308: Annotations on Java Types 
www.luxoft.com
Target Typing 
Map<Integer, List<String>> map = new HashMap<>(); 
... 
map.put(key, Collections.emptyList()); 
public <E> void process(List<E> list, Class<E> type) {...} 
... 
process(new ArrayList<>(), String.class) 
www.luxoft.com
Target Typing 
www.luxoft.com 
List<Number> numbers = Arrays.asList(1,2,3); 
Iterator<String> iterator = new ArrayList<>().iterator();
Annotation Type Target 
 ANNOTATION_TYPE 
 CONSTRUCTOR 
 FIELD 
 LOCAL_VARIABLE 
 METHOD 
 PACKAGE 
 PARAMETER 
 TYPE 
 TYPE_PARAMETER 
 TYPE_USE 
www.luxoft.com 
Java 8
Type annotations usage 
 generic type arguments 
List<@Localized Document> files; 
 type parameter bounds 
Collection<? @NotNull Number> files; 
 class inheritance 
class UnmodifiableList<T> implements @Readonly List<T> {...} 
www.luxoft.com
Type annotations location 
 object creation 
new @Interned MyObject(); 
 casting 
myString = (@NonNull String) myObject; 
 throwing exceptions 
void update() throws @Critical DataAccessException { ... } 
www.luxoft.com
www.luxoft.com 
The Java 8 release does not 
provide a type checking framework
Checker Framework 
 Nullness Checker 
 Interning Checker 
 Lock Checker 
 Fake Enum Checker 
 Tainting Checker 
www.luxoft.com 
 Regex Checker 
 Format String Checker 
 Property File Checker 
 Signature Checker 
 Immutability Checker
Example 1. NulnessChecker 
import org.checkerframework.checker.nullness.qual.Nullable; 
public class NullnessExample { 
www.luxoft.com 
public String buildMessage(@Nullable String str) { 
return "Message: " + str.toLowerCase(); 
} 
} 
javac -processor org.checkerframework.checker.nullness.NullnessChecker ... 
Compile-time error
Example 1. NulnessChecker 
import org.checkerframework.checker.nullness.qual.Nullable; 
public class NullnessExample1 { 
www.luxoft.com 
public String buildMessage(@Nullable String str) { 
if (str != null) { 
return "Message: " + str.toLowerCase(); 
} 
return ""; 
} 
} 
Compiles successfully
Example 2. Tainting Checker 
import org.checkerframework.checker.tainting.qual.Tainted; 
import org.checkerframework.checker.tainting.qual.Untainted; 
public class TainedExample { 
www.luxoft.com 
public void execute(@Tainted String id) { 
String query = buildQuery(id); 
//... 
} 
public String buildQuery(@Untainted String id) { 
return "SELECT p.name FROM product p where p.id = " + id; 
} 
} 
javac -processor org.checkerframework.checker.tainting.TaintingChecker ... 
Compile-time error
Example 2. Tainting Checker 
import org.checkerframework.checker.tainting.qual.Tainted; 
import org.checkerframework.checker.tainting.qual.Untainted; 
public class TainedExample { 
www.luxoft.com 
public void execute(@Tainted String id) { 
String query = buildQuery(verify(id)); 
//... 
} 
public @Untainted String verify(@Tainted String id) { 
if (id.matches(".*D.*")) { 
throw new IllegalArgumentException("String contains invalid chars!"); 
} 
return new @Untainted String(id); 
} 
public String buildQuery(@Untainted String id) { 
return "SELECT p.name FROM product p where p.id = " + id; 
} 
} 
Compiles successfully
Example 3. Immutability Checker 
import org.checkerframework.checker.javari.qual.ReadOnly; 
import java.util.*; 
public class MutabilityExample { 
www.luxoft.com 
public void example() { 
ImmutableClass obj = new ImmutableClass(); 
obj.getValues().add("test"); 
} 
private class ImmutableClass { 
private List<String> values = new ArrayList<>(); 
public @ReadOnly List<String> getValues() { 
return values; 
} 
} 
} 
javac -processor org.checkerframework.checker.javari.JavariChecker ...
Project Valhalla 
 Value Types 
 Generic Specialization 
 Reified generics ? 
www.luxoft.com
“Codes like a class, works like an int!” © 
Java type system aggregate data types 
• heterogeneous aggregates with identity (classes) 
• homogeneous aggregates with identity (arrays) 
Object identity => footprint and performance costs 
Value types: identityless, immutable, pointer-free aggregates 
www.luxoft.com
Value Types use cases 
 Numerics 
 Native types 
 Algebraic data types 
 Tuples 
 Cursors 
 Flatting 
www.luxoft.com
Generic Specialization 
Goal: support generics over primitives and value types 
Specialization approaches 
• ahead-of-time (Scala) 
• on-demand (C#) 
class Box<T> { 
www.luxoft.com 
private final T t; 
public Box(T t) { this.t = t; } 
public T get() { return t; } 
}
Bytecode (current JVM version) 
class Box extends java.lang.Object{ 
private final java.lang.Object t; 
public Box(java.lang.Object); 
www.luxoft.com 
Code: 
0: aload_0 
1: invokespecial #1; //Method java/lang/Object."<init>":()V 
4: aload_0 
5: aload_1 
6: putfield #2; //Field t:Ljava/lang/Object; 
9: return 
public java.lang.Object get(); 
Code: 
0: aload_0 
1: getfield #2; //Field t:Ljava/lang/Object; 
4: areturn 
}
Bytecode marked up to preserve erasure information (proposed) 
class Box extends java.lang.Object{ 
private final java.lang.Object*T t; 
public Box(java.lang.Object*T); 
www.luxoft.com 
Code: 
0: aload_0 
1: invokespecial #1; //Method java/lang/Object."<init>":()V 
4: aload_0 
5: aload_1*T 
6: putfield #2; //Field t:Ljava/lang/Object*T; 
9: return 
public java.lang.Object* get(); 
Code: 
0: aload_0 
1: getfield #2; //Field t:Ljava/lang/Object*T; 
4: areturn*T 
}
Bytecode after specialization 
class Box${T=int} extends java.lang.Object{ 
private final int t; 
public Box${T=int}(int); 
Code: 
0: aload_0 
1: invokespecial #1; //Method java/lang/Object."<init>":()V 
4: aload_0 
5: iload_1 
6: putfield #2; //Field t:int; 
9: return 
public int get(); 
Code: 
0: aload_0 
1: getfield #2; //Field t:int; 
4: ireturn 
} 
www.luxoft.com
Links 
1. https://www.oracle.com/javaone/sessions/index.html Daniel Smith. Type Inference in Java SE 8. 
2. http://2013.javapoint.ru/talks/21/ Александр Ильин. Type annotations in Java 8. И почему это хорошо. 
3. http://types.cs.washington.edu/checker-framework/ The Checker Framework 
4. http://mail.openjdk.java.net/pipermail/valhalla-dev/2014-July/000000.html Welcome to Valhalla 
5. http://cr.openjdk.java.net/~jrose/values/values-0.html John Rose, Brian Goetz, and Guy Steele. State of 
the Values. April 2014: Infant Edition 
6. http://cr.openjdk.java.net/~briangoetz/valhalla/specialization.html Brian Goetz. State of Specialization. 
Jule 2014: Infant Edition 
www.luxoft.com
www.luxoft.com 
Q/A

More Related Content

What's hot

Advance unittest
Advance unittestAdvance unittest
Advance unittest
Reza Arbabi
 
TDD? Sure, but What About My Legacy Code?
TDD? Sure, but What About My Legacy Code?TDD? Sure, but What About My Legacy Code?
TDD? Sure, but What About My Legacy Code?
Rob Myers
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012
Yaqi Zhao
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
Mody Farouk
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
g_hemanth17
 

What's hot (20)

C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
Inner classes
Inner classesInner classes
Inner classes
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
 
Advance unittest
Advance unittestAdvance unittest
Advance unittest
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve Mobile
 
TDD? Sure, but What About My Legacy Code?
TDD? Sure, but What About My Legacy Code?TDD? Sure, but What About My Legacy Code?
TDD? Sure, but What About My Legacy Code?
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012
 
UI testing in Xcode 7
UI testing in Xcode 7UI testing in Xcode 7
UI testing in Xcode 7
 
Generating characterization tests for legacy code
Generating characterization tests for legacy codeGenerating characterization tests for legacy code
Generating characterization tests for legacy code
 
Java2
Java2Java2
Java2
 
Modul Praktek Java OOP
Modul Praktek Java OOP Modul Praktek Java OOP
Modul Praktek Java OOP
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 

Similar to Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»

Similar to Дмитрий Контрерас «Back to the future: the evolution of the Java Type System» (20)

Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Java Tutorial 1
Java Tutorial 1Java Tutorial 1
Java Tutorial 1
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
 
Server1
Server1Server1
Server1
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
 
Java practical
Java practicalJava practical
Java practical
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
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)
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
Android testing
Android testingAndroid testing
Android testing
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 

More from Anna Shymchenko

More from Anna Shymchenko (20)

Константин Маркович: "Creating modular application using Spring Boot "
Константин Маркович: "Creating modular application using Spring Boot "Константин Маркович: "Creating modular application using Spring Boot "
Константин Маркович: "Creating modular application using Spring Boot "
 
Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...
Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...
Евгений Бова: "Modularity in Java: introduction to Jigsaw through the prism o...
 
Евгений Руднев: "Programmers Approach to Error Handling"
Евгений Руднев: "Programmers Approach to Error Handling"Евгений Руднев: "Programmers Approach to Error Handling"
Евгений Руднев: "Programmers Approach to Error Handling"
 
Александр Куцан: "Static Code Analysis in C++"
Александр Куцан: "Static Code Analysis in C++" Александр Куцан: "Static Code Analysis in C++"
Александр Куцан: "Static Code Analysis in C++"
 
Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club”
Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club” Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club”
Алесей Решта: “Robotics Sport & Luxoft Open Robotics Club”
 
Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"
 
Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"
Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"
Евгений Хыст: "Server-Side Geo-Clustering Based on Geohash"
 
Денис Прокопюк: “JMX in Java EE applications”
Денис Прокопюк: “JMX in Java EE applications”Денис Прокопюк: “JMX in Java EE applications”
Денис Прокопюк: “JMX in Java EE applications”
 
Роман Яворский "Introduction to DevOps"
Роман Яворский "Introduction to DevOps"Роман Яворский "Introduction to DevOps"
Роман Яворский "Introduction to DevOps"
 
Максим Сабарня “NoSQL: Not only SQL in developer’s life”
Максим Сабарня “NoSQL: Not only SQL in developer’s life” Максим Сабарня “NoSQL: Not only SQL in developer’s life”
Максим Сабарня “NoSQL: Not only SQL in developer’s life”
 
Андрей Лисниченко "SQL Injection"
Андрей Лисниченко "SQL Injection"Андрей Лисниченко "SQL Injection"
Андрей Лисниченко "SQL Injection"
 
Светлана Мухина "Metrics on agile projects"
Светлана Мухина "Metrics on agile projects"Светлана Мухина "Metrics on agile projects"
Светлана Мухина "Metrics on agile projects"
 
Андрей Слободяник "Test driven development using mockito"
Андрей Слободяник "Test driven development using mockito"Андрей Слободяник "Test driven development using mockito"
Андрей Слободяник "Test driven development using mockito"
 
Евгений Хыст "Application performance database related problems"
Евгений Хыст "Application performance database related problems"Евгений Хыст "Application performance database related problems"
Евгений Хыст "Application performance database related problems"
 
Даурен Муса “IBM WebSphere - expensive but effective”
Даурен Муса “IBM WebSphere - expensive but effective” Даурен Муса “IBM WebSphere - expensive but effective”
Даурен Муса “IBM WebSphere - expensive but effective”
 
Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"Александр Пашинский "Reinventing Design Patterns with Java 8"
Александр Пашинский "Reinventing Design Patterns with Java 8"
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
 
Event-driven architecture with Java technology stack
Event-driven architecture with Java technology stackEvent-driven architecture with Java technology stack
Event-driven architecture with Java technology stack
 
Do we need SOLID principles during software development?
Do we need SOLID principles during software development?Do we need SOLID principles during software development?
Do we need SOLID principles during software development?
 
Guava - Elements of Functional Programming
Guava - Elements of Functional Programming Guava - Elements of Functional Programming
Guava - Elements of Functional Programming
 

Recently uploaded

Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 

Recently uploaded (20)

Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by Skilrock
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 

Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»

  • 1. Back to the future: Evolution of the Java Type System www.luxoft.com
  • 2. Agenda  History: Java 5 Type System  Generalized Target-Type Inference  Annotated Types  Checker Framework  Project Valhalla www.luxoft.com
  • 3. Java 5 Type System  Parametric polymorphism public class Sample<T> {  Bounded wildcards  Intersection types  Type erasure www.luxoft.com private T data; public T getData() { ... } } Collection<? extends Serializable> public class Box<T extends Comparable & Clonable> { ...
  • 4. Java 8 Type System  JEP 101: Generalized Target-Type Inference - Add support for method type-parameter inference in method context - Add support for method type-parameter inference in chained calls  JSR 308: Annotations on Java Types www.luxoft.com
  • 5. Target Typing Map<Integer, List<String>> map = new HashMap<>(); ... map.put(key, Collections.emptyList()); public <E> void process(List<E> list, Class<E> type) {...} ... process(new ArrayList<>(), String.class) www.luxoft.com
  • 6. Target Typing www.luxoft.com List<Number> numbers = Arrays.asList(1,2,3); Iterator<String> iterator = new ArrayList<>().iterator();
  • 7. Annotation Type Target  ANNOTATION_TYPE  CONSTRUCTOR  FIELD  LOCAL_VARIABLE  METHOD  PACKAGE  PARAMETER  TYPE  TYPE_PARAMETER  TYPE_USE www.luxoft.com Java 8
  • 8. Type annotations usage  generic type arguments List<@Localized Document> files;  type parameter bounds Collection<? @NotNull Number> files;  class inheritance class UnmodifiableList<T> implements @Readonly List<T> {...} www.luxoft.com
  • 9. Type annotations location  object creation new @Interned MyObject();  casting myString = (@NonNull String) myObject;  throwing exceptions void update() throws @Critical DataAccessException { ... } www.luxoft.com
  • 10. www.luxoft.com The Java 8 release does not provide a type checking framework
  • 11. Checker Framework  Nullness Checker  Interning Checker  Lock Checker  Fake Enum Checker  Tainting Checker www.luxoft.com  Regex Checker  Format String Checker  Property File Checker  Signature Checker  Immutability Checker
  • 12. Example 1. NulnessChecker import org.checkerframework.checker.nullness.qual.Nullable; public class NullnessExample { www.luxoft.com public String buildMessage(@Nullable String str) { return "Message: " + str.toLowerCase(); } } javac -processor org.checkerframework.checker.nullness.NullnessChecker ... Compile-time error
  • 13. Example 1. NulnessChecker import org.checkerframework.checker.nullness.qual.Nullable; public class NullnessExample1 { www.luxoft.com public String buildMessage(@Nullable String str) { if (str != null) { return "Message: " + str.toLowerCase(); } return ""; } } Compiles successfully
  • 14. Example 2. Tainting Checker import org.checkerframework.checker.tainting.qual.Tainted; import org.checkerframework.checker.tainting.qual.Untainted; public class TainedExample { www.luxoft.com public void execute(@Tainted String id) { String query = buildQuery(id); //... } public String buildQuery(@Untainted String id) { return "SELECT p.name FROM product p where p.id = " + id; } } javac -processor org.checkerframework.checker.tainting.TaintingChecker ... Compile-time error
  • 15. Example 2. Tainting Checker import org.checkerframework.checker.tainting.qual.Tainted; import org.checkerframework.checker.tainting.qual.Untainted; public class TainedExample { www.luxoft.com public void execute(@Tainted String id) { String query = buildQuery(verify(id)); //... } public @Untainted String verify(@Tainted String id) { if (id.matches(".*D.*")) { throw new IllegalArgumentException("String contains invalid chars!"); } return new @Untainted String(id); } public String buildQuery(@Untainted String id) { return "SELECT p.name FROM product p where p.id = " + id; } } Compiles successfully
  • 16. Example 3. Immutability Checker import org.checkerframework.checker.javari.qual.ReadOnly; import java.util.*; public class MutabilityExample { www.luxoft.com public void example() { ImmutableClass obj = new ImmutableClass(); obj.getValues().add("test"); } private class ImmutableClass { private List<String> values = new ArrayList<>(); public @ReadOnly List<String> getValues() { return values; } } } javac -processor org.checkerframework.checker.javari.JavariChecker ...
  • 17. Project Valhalla  Value Types  Generic Specialization  Reified generics ? www.luxoft.com
  • 18. “Codes like a class, works like an int!” © Java type system aggregate data types • heterogeneous aggregates with identity (classes) • homogeneous aggregates with identity (arrays) Object identity => footprint and performance costs Value types: identityless, immutable, pointer-free aggregates www.luxoft.com
  • 19. Value Types use cases  Numerics  Native types  Algebraic data types  Tuples  Cursors  Flatting www.luxoft.com
  • 20. Generic Specialization Goal: support generics over primitives and value types Specialization approaches • ahead-of-time (Scala) • on-demand (C#) class Box<T> { www.luxoft.com private final T t; public Box(T t) { this.t = t; } public T get() { return t; } }
  • 21. Bytecode (current JVM version) class Box extends java.lang.Object{ private final java.lang.Object t; public Box(java.lang.Object); www.luxoft.com Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: aload_0 5: aload_1 6: putfield #2; //Field t:Ljava/lang/Object; 9: return public java.lang.Object get(); Code: 0: aload_0 1: getfield #2; //Field t:Ljava/lang/Object; 4: areturn }
  • 22. Bytecode marked up to preserve erasure information (proposed) class Box extends java.lang.Object{ private final java.lang.Object*T t; public Box(java.lang.Object*T); www.luxoft.com Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: aload_0 5: aload_1*T 6: putfield #2; //Field t:Ljava/lang/Object*T; 9: return public java.lang.Object* get(); Code: 0: aload_0 1: getfield #2; //Field t:Ljava/lang/Object*T; 4: areturn*T }
  • 23. Bytecode after specialization class Box${T=int} extends java.lang.Object{ private final int t; public Box${T=int}(int); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: aload_0 5: iload_1 6: putfield #2; //Field t:int; 9: return public int get(); Code: 0: aload_0 1: getfield #2; //Field t:int; 4: ireturn } www.luxoft.com
  • 24. Links 1. https://www.oracle.com/javaone/sessions/index.html Daniel Smith. Type Inference in Java SE 8. 2. http://2013.javapoint.ru/talks/21/ Александр Ильин. Type annotations in Java 8. И почему это хорошо. 3. http://types.cs.washington.edu/checker-framework/ The Checker Framework 4. http://mail.openjdk.java.net/pipermail/valhalla-dev/2014-July/000000.html Welcome to Valhalla 5. http://cr.openjdk.java.net/~jrose/values/values-0.html John Rose, Brian Goetz, and Guy Steele. State of the Values. April 2014: Infant Edition 6. http://cr.openjdk.java.net/~briangoetz/valhalla/specialization.html Brian Goetz. State of Specialization. Jule 2014: Infant Edition www.luxoft.com