28,14 €
Enhance your development skills with Java's state-of-the-art features and projects to make your applications leaner and faster
Key Features
Book Description
With its new six-monthly release cadence, Java is moving forward faster. In addition to planned version releases, a lot of work is currently being undertaken on various Java projects at Oracle. In order to make best use of the new features in their applications and libraries, you must be well-versed with the most recent advancements.
Java 11 and 12 – New Features will take you through the latest developments in Java, right from variable type inference and simplified multithreading through to performance improvements, which are covered in depth to help you make your applications more efficient. This book explains the relevance and applicability of Java's new features, and answers your questions on whether to invest in migrating to new Java versions and when to migrate. You'll also get to grips with platform features, such as AppCDS and new garbage collectors, to tune and optimize your application—from reduced launch time and latency to improved performance and throughput.
By the end of this book, you will be equipped with a thorough understanding of the new features of Java 11, 12, and Project Amber, and possess the skills to apply them with a view to improving your application's performance.
What you will learn
Who this book is for
If you're an executive or solutions architect responsible for technology selection or Java migration decisions, this Java book is for you. You'll also benefit from this book if you're a computer science enthusiast curious to learn about the latest and upcoming Java features. This book will help you migrate your solutions from Java 8 or older to the latest Java release.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 244
Veröffentlichungsjahr: 2019
BIRMINGHAM - MUMBAI
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Aaron LazarAcquisition Editor: Alok DhuriContent Development Editor: Rohit SinghTechnical Editor: Gaurav GalaCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Priyanka DhadkeGraphics: Alishon MendonsaProduction Coordinator: Deepika Naik
First published: March 2019
Production reference: 1220319
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78913-327-1
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Mala Gupta, a Java champion, works as a developer advocate for JetBrains. The founder of eJavaGuru, she has been actively supporting Java certification as a path to career advancement. Since 2006, she has been coaching students and professionals with a view to achieving success in these certifications.
A frequent speaker at industry conferences, her Java books with Manning Publications, USA, are top-rated for Oracle certification around the globe. She has over 18 years of experience in the software industry. Mala has also co-founded KaagZevar, a platform for nurturing creativity as an essential life skill. She co-leads the Delhi Java User Group. As the Director of Women Who Code Delhi, she also drives initiatives for diversity advocacy for Women in Technology.
Marcus Biel works as the customer experience director for Red Hat. He is a well-known software craftsman, Java influencer, and Clean Code Evangelist. He is also a regular speaker at Java conferences all over the world, such as JBCN Conf Barcelona, JPoint Moscow, and JAX London. Furthermore, he has worked as a technical reviewer for renowned Java publications, including Effective Java, Core Java SE 9 for the Impatient, or Java by Comparison. Marcus has worked on various Java-related projects since 2001, mainly in the financial and telecommunications industries.
When taking a break from Java, he likes hiking in the Alps, as well as backpacking, dancing, and enjoying a good beer or wine. He lives with his wife and baby son.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Java 11 and 12 – New Features
About Packt
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Section 1: JDK 10
Type Inference
What is type inference?
Type inference with var
Compulsory non-null initialization
Local variables
Code check – part 1
Using var with primitive data types
Type inference with derived classes
Type inference with interfaces
Using var with arrays
Type inference with generics
Code check – part 2
Passing inferred variables to a method
Reassigning values to inferred variables
Explicit casting with inferred variables
Assigning null with explicit casting
Type inference in previous versions of Java
Type inference in Java 5
Type inference in Java 7
Type inference in Java 8
Challenges
Limiting the scope of failed assumptions
Breaking existing code
Non-denotable types
Meaningful variable names
Code refactoring
Type inference versus dynamic binding
Summary
AppCDS
Technical requirements
What is CDS?
Location of the shared archive file
Manual creation of classes.jsa
Usage of CDS
AppCDS
Benefits of AppCDS
Enabling application class data archive
Which application classes to archive
Creating an application shared archive file
Using the shared application archive file
Summary
Garbage Collector Optimizations
Technical requirements
The GC interface 
Benefits
Driving factors
Impact
Parallel full GC for G1 (JEP 307)
The design goals of G1 GC
G1 memory
Sample code
Understanding G1 GC logs
Summary
Miscellaneous Improvements in JDK 10
Technical requirements
Mapping JDK 10 features with scopes and JEPs
Consolidating the JDK forest into a single repository
Thread-local handshakes
Removal of the Native-Header Generation Tool (javah)
Additional Unicode language-tag extensions
Heap allocation on alternative memory devices
The experimental Java-based JIT compiler
Root certificates
Time-based release versioning
Summary
Section 2: JDK 11
Local Variable Syntax for Lambda Parameters
Technical requirements
Lambda expressions
Explicitly-typed lambda expressions
Implicitly-typed lambda expressions
Lambda parameters and type inference with var
Adding var to lambda parameters
Adding annotations to lambda parameters
Summary
Epsilon GC
Technical requirements
The motivation behind Epsilon GC
Features of Epsilon
Latency and application performance
GC-induced overheads versus system overheads
Extremely short-lived work
Getting started with the HelloEpsilon GC class
Which memory area does GC collect – stack or heap?
Memory pressure testing with Epsilon
Designing a garbage-free application
VM interface testing
Summary
The HTTP Client API
Technical requirements
A quick flashback
What can you do with HTTP?
The need for the HTTP Client API
HTTP Client usage
A basic example
The HttpClient class 
Creating an HttpClient instance
Methods of the HttpClient class 
HttpRequest
HttpResponse
Some examples
Accessing HTML pages using synchronous GET
Accessing HTML pages using asynchronous GET
Downloading multiple hosted image files
Posting form details
Summary
ZGC
Technical requirements
The motivation
Features of ZGC
Getting started with ZGC
ZGC heap
ZGC phases
Colored pointers
Tuning ZGC
Summary
Flight Recorder and Mission Control
Technical requirements
The motivation behind JFR
Features
Modules
Getting started with JFR
Exploring further
Working with custom events
Summary
Miscellaneous Improvements in JDK 11
Technical requirements
Listing the JEPs that are used in this chapter
Nest-based access control
What is nest-based access?
Affects of nest-based control
Dynamic class-file constants
Improving AArch64 intrinsics
Removing the Java EE and CORBA modules
A key agreement with Curve25519 and Curve448
Unicode 10
ChaCha20 and Poly1305 cryptographic algorithms
Launching single file source code programs
TLS 1.3
Deprecating the Nashorn JavaScript engine
JEP 336 – deprecating the pack200 tools and API
Summary
Section 3: JDK 12
Switch Expressions
Technical requirements
Issues with traditional switch constructs
Using switch expressions
Defining local variables in a switch branch
Another syntax for switch expressions
Comparing break with break <return value>
A preview language feature
Exhaustive cases
What can a switch branch execute other than returning a value?
How not to use labels and continue in switch expressions
Summary
Miscellaneous Improvements in JDK 12
Technical requirements
Mapping features of JDK 12 scope and JEP
Shenandoah – a low-pause-time GC
The microbenchmark suite
The JVM constants API
One AArch64 port, not two
Default CDS archives
What is CDS?
Enhancing CDS
Abortable mixed collections for G1
Promptly return unused committed memory from G1
Summary
Section 4: Project Amber
Enhanced Enums in Project Amber
A quick background
An example
Decompiled enum – behind the scenes
The state and behavior of enum constants
Adding states and behaviors to enum constants
Accessing the state and behavior of enum constants
Workarounds to access enum constants
Using inheritance with enum constants
Adding generics to enums
Sharper typing of enum constants
Summary
Data Classes and Their Usage
An introduction to data classes
What is a data class?
The need to add data classes to the language
Diving into data classes
Example of syntax and semantics
The aggregate and exploded forms of data classes
Limitations
Examples from the past – changes to define enums
Pattern matching with data classes
Encapsulating the state
Abstract and non-abstract data classes
Data classes and inheritance
Extending an abstract data class
Implementing interfaces
Additional variables
Overriding implicit behaviors
Additional methods and constructors
Mutability
Summary
Raw String Literals
Technical requirements
A quick example
Issues with existing multiline string values
A simple task
Escape sequence hell with traditional string literals
Concatenation hell with traditional string literals
Including escape sequences as part of string values
Strings and regex patterns, another hell
Welcoming raw string literals
Rewriting using raw strings
The delimiter (backtick)
Treating escape values
Raw string literals versus traditional string literals
Interpreting escape sequences
The unescape() method
The escape() method
Managing margins
The align() method
The indent(int) method
The overloaded align(int) method
The detab(int) and entab methods
The transform() method
Common examples
JSON data
XML data
File paths
Database queries
Summary
Lambda Leftovers
Technical requirements
Marking unused parameters with underscores
An example of lambda parameters
The journey of getting there
Shadowing of lambda parameters
The existing case of lambda parameters
Why should lambda parameters overshadow enclosing variables?
A few of the known issues
Disambiguation of functional expressions
Issues with resolving overloaded methods – passing lambdas 
Issues with resolving overloaded methods – passing method references
The proposed solution
Summary
Pattern Matching
Technical requirements
Pattern matching
Existing issues with type testing
Type test patterns
Using pattern matching with switch constructs
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
With Java moving forward at a great pace, programmers must be aware of the latest developments to make the best use of its newer features in their applications and libraries.
This book will take you through the developments in the Java language, right from Java 10, to Java 11, and Java 12. The book deep dives into the latest developments in the language. You'll learn how these features can help you advance your development with the language and make your applications leaner and faster.
You'll also discover features to configure your virtual machine to reduce startup time, so as to solve throughput and latency challenges in the future. With the help of this book, you will overcome the challenges involved in migrating to new versions of Java.
If you're an executive or solutions architect responsible for technology selection or Java migration decisions, this Java book is for you. You'll also benefit from this book if you're a computer science enthusiast curious to learn about the latest, and upcoming, Java features. Java 11 and 12 – New Features will help you migrate your solutions from Java 8 or previous versions to the latest Java release.
Chapter 1,Type Inference, introduces type inference with local variables, which was introduced in Java 10. You will learn how to use the var keyword and also the challenges involved.
Chapter 2, AppCDS, covers Application Class-Data Sharing (AppCDS), which extends Class-Data Sharing (CDS). You will learn about both and see them in action.
Chapter 3,Garbage Collector Optimizations, discusses the various GCs and their interfaces for efficient implementation.
Chapter 4,Miscellaneous Improvements in JDK 10, covers the features and improvements in Java 10.
Chapter 5,Local Variable Syntax for Lambda Parameters, explainsthe local variable syntax for lambda parameters with an introduction to the usage of var with lambda parameters. This chapter also covers its syntax and usage, along with the challenges you may face.
Chapter 6,Epsilon GC, exploreshow Java 11 introduces Epsilon, which reduces the latency in garbage collection. This chapter explains why it is required and its design considerations.
Chapter 7,The HTTP Client API, talks about the HTTP Client API, which enables your Java code to request HTTP resources over a network.
Chapter 8, ZGC, explores a new GC called ZGC, which is scalable with low latency. You will learn about its features and work through examples.
Chapter 9, Flight Recorder and Mission Control, talks about the JFR profiler, which helps to record data, and the MC tool, which helps in the analysis of the collected data.
Chapter 10, Miscellaneous Improvements in JDK 11, covers the features and improvements in Java 11.
Chapter 11, Switch Expressions, covers switch expressions, which are a basic language construct enhanced in Java 12. You will learn how to use these to make your code more efficient.
Chapter 12, Miscellaneous Improvements in JDK 12, covers the features and improvements in Java 12.
Chapter 13,Enhanced Enums in Project Amber, shows how enums introduced type safety to constants. This chapter also covers how each enum constant can have its own distinct state and behavior.
Chapter 14,Data Classes and Their Usage, covers how the data classes in Project Amber are bringing about language changes to define data carrier classes.
Chapter 15, Raw String Literals, covers the challenges that developers face when storing various types of multiline text values as string values. Raw string literals address these concerns, also significantly improving the writability and readability of multiline string values.
Chapter 16, Lambda Leftovers, shows how the lambda leftovers project is improving the functional programming syntax and experience in Java.
Chapter 17, Pattern Matching, works through coding examples to help you understand how pattern matching can change how you write everyday code.
Some prior Java knowledge will be beneficial and all the requisite instructions are added to the respective chapters.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Java-11-and-12-New-Features. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789133271_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
This section will help you get started with type inferencing, which was one of the main features of Java 10. We will then learn about application class data sharing, which helps in selecting application classes in the shared archived files. Moving on, we will explore more about the GC interface and parallel full GC for G1. Lastly, we will cover the remaining additions or updates to Java 10, most of which are related to changes in the JDK or its implementation.
The following chapters will be covered in this section:
Chapter 1
,
Type Inference
Chapter 2
,
AppCDS
Chapter 3
,
Garbage Collector Optimizations
Chapter 4
,
Miscellaneous Improvements in JDK 10
The ability to use type inference with local variables (var) is one of the star features of Java 10. It reduces the verbosity of the language without compromising Java's dependable static binding and type safety. The compiler infers the type by using the information available in the code, and adds it to the bytecode that it generates.
Every new concept has its own set of benefits, limitations, and complexities. Using type inference with var is no exception. As you work through this chapter, using var will enthrall and frustrate you, but you will emerge triumphantly.
In this chapter, we'll cover the following topics:
What is type inference?
Type inference with
var
Dos and don'ts of working with
var
Type inference versus dynamic binding
Imagine solving a riddle, such as the one shown in the following image, with multiple constraints in the form of hints. You resolve the constraints to derive the answer. You can compare type inference to generating constraints and then resolving them, in order to determine the data types in a programming language. Type inference is the capability of the compiler to determine the type of the data, by using the information that is already available in the code—literal values, method invocations, and their declarations. For a developer, type inference reduces verbosity, as indicated by the following diagram:
For your reference, the answer to the preceding riddle is 87 (just turn the image upside down, and you'll find the numbers in a sequence).
Let's dive into the topic by looking at some examples of var.
