46,44 €
Solutions for modular, functional, reactive, GUI, network, and multithreaded programming
Key Features
Book Description
For more than three decades, Java has been on the forefront of developing robust software that has helped versatile businesses meet their requirements. Being one of the most widely used programming languages in history, it's imperative for Java developers to discover effective ways of using it in order to take full advantage of the power of the latest Java features. Java 11 Cookbook offers a range of software development solutions with simple and straightforward Java 11 code examples to help you build a modern software system.
Starting with the installation of Java, each recipe addresses various problem by explaining the solution and offering insights into how it works. You'll explore the new features added to Java 11 that will make your application modular, secure, and fast. The book contains recipes on functional programming, GUI programming, concurrent programming, and database programming in Java. You'll also be taken through the new features introduced in JDK 18.3 and 18.9.
By the end of this book, you'll be equipped with the skills required to write robust, scalable, and optimal Java code effectively.
What you will learn
Who this book is for
The book is for intermediate-to-advanced Java programmers who want to make their applications fast, secure, and scalable.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 829
Veröffentlichungsjahr: 2018
Copyright © 2018 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 authors, 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: Richa TripathiAcquisition Editor: Denim PintoContent Development Editor: Pooja ParvatkarTechnical Editor: Mehul SinghCopy Editor:Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Rekha NairGraphics: Tom ScariaProduction Coordinator: Arvindkumar Gupta
First published: August 2017 Second edition: September 2018
Production reference: 1210918
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78913-235-9
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.
Nick Samoylov graduated as an engineer-physicist from Moscow Institute of Physics and Technology, has worked as a theoretical physicist, and learned how to program as a tool for testing his mathematical models using FORTRAN and C++. After the demise of the USSR, Nick created and successfully ran a software company, but was forced to close it under pressure from governmental and criminal rackets. In 1999, with his wife Luda and two daughters, he emigrated to the USA and has been living in Colorado since then, working as a Java programmer. In his free time, Nick likes to read (mostly non-fiction), write (fiction novels and blogs), and hike the Rocky Mountains.
Mohamed Sanaulla is a full-stack developer with more than 8 years, experience in developing enterprise applications and Java-based backend solutions for e-commerce applications. His interests include enterprise software development, refactoring and redesigning applications, designing and implementing RESTful web services, troubleshooting Java applications for performance issues, and TDD. He has strong expertise in Java-based application development, ADF (a JSF-based Java EE web framework), SQL, PL/SQL, JUnit, designing RESTful services, Spring, Spring Boot, Struts, Elasticsearch, and MongoDB. He is also a Sun Certified Java Programmer for the Java 6 platform. He is a moderator for JavaRanch and likes to share his findings on his blog.
Aristides Villarreal Bravo is a Java developer, a member of the NetBeans Dream Team, and a Java User Groups leader. He lives in Panama. He has organized and participated in various conferences and seminars related to Java, JavaEE, NetBeans, the NetBeans platform, free software, and mobile devices. He is the author of jmoordb and tutorials and blogs about Java, NetBeans, and web development. Aristides has participated in several interviews on sites about topics such as NetBeans, NetBeans DZone, and JavaHispano. He is a plugin developer for NetBeans.
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 Cookbook Second Edition
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the authors
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
Conventions used
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Get in touch
Reviews
Installation and a Sneak Peek into Java 11
Introduction
Installing JDK 18.9 on Windows and setting up the PATH variable
How to do it...
Installing JDK 18.9 on Linux (Ubuntu, x64) and configuring the PATH variable
How to do it...
Compiling and running a Java application
Getting ready
How to do it...
What's new in Java 11?
Getting ready
How to do it...
JEP 318 – Epsilon
JEP 321 – HTTP Client (Standard)
JEP 323 – Local-Variable Syntax for Lambda Parameters
JEP 333 – ZGC
New API
There's more...
Using application class-data sharing
Getting ready
How to do it...
Fast Track to OOP - Classes and Interfaces
Introduction
Implementing object-oriented design (OOD)
Getting ready
How to do it...
How it works...
There's more...
Using inner classes
Getting ready
How to do it...
How it works...
There's more...
Using inheritance and aggregation
Getting ready
How to do it...
How it works...
Aggregation makes the design more extensible
Coding to an interface
Getting ready
How to do it...
How it works...
There's more...
Creating interfaces with default and static methods
Getting ready
How to do it...
How it works...
Creating interfaces with private methods
Getting ready
How to do it...
How it works...
There's more...
A better way to work with nulls using Optional
Getting ready
How to do it...
How it works...
There's more...
Using the utility class Objects
Getting ready
How to do it...
How it works...
Modular Programming
Introduction
Using jdeps to find dependencies in a Java application
Getting ready
How to do it...
How it works...
There's more...
Creating a simple modular application
Getting ready
How to do it...
How it works...
See also
Creating a modular JAR
Getting ready
How to do it...
Using a module JAR with pre-Project Jigsaw JDK applications
Getting ready
How to do it...
Bottom-up migration
Getting ready
How to do it...
Modularizing banking.util.jar
Modularizing math.util.jar
Modularizing calculator.jar
How it works...
Top-down migration
Getting ready
How to do it...
Modularizing the calculator
Modularizing banking.util
Modularizing math.util
Using services to create loose coupling between the consumer and provider modules
Getting ready
How to do it...
Creating a custom modular runtime image using jlink
Getting ready
How to do it...
Compiling for older platform versions
Getting ready
How to do it...
How it works...
Creating multi-release JARs
How to do it...
How it works...
Using Maven to develop a modular application
Getting ready
How to do it...
Making your library module-path-friendly
Getting ready
How to do it...
How it works...
There's more... 
How to open a module for reflection
Getting ready
How to do it...
How it works...
Going Functional
Introduction
Using standard functional interfaces
Getting ready
How to do it...
How it works...
There's more...
Creating a functional interface
Getting ready
How to do it...
How it works...
There's more...
Understanding lambda expressions
Getting ready
How to do it...
How it works...
There's more...
Using lambda expressions
Getting ready
How to do it...
How it works...
There's more...
Using method references
Getting ready
How to do it...
Static unbound method reference
Non-static bound method reference
Non-static unbound method reference
Constructor method references
There's more...
Leveraging lambda expressions in your programs
Getting ready
How to do it...
There's more...
Streams and Pipelines
Introduction
Creating immutable collections using the of() and copyOf() factory methods
Getting ready
How to do it...
There's more...
Creating and operating on streams
Getting ready
How to do it...
How it works...
Using numeric streams for arithmetic operations
Getting ready
How to do it...
There's more...
Completing streams by producing collections
Getting ready
How to do it...
Completing streams by producing maps
Getting ready
How to do it...
Completing streams by producing maps using grouping collectors
Getting ready
How to do it...
There's more...
Creating stream operation pipeline
Getting ready
How to do it...
There's more...
Processing streams in parallel
Getting ready
How to do it...
Database Programming
Introduction
Connecting to a database using JDBC
How to do it...
How it works...
There's more...
Setting up the tables required for DB interactions
Getting ready
How it works...
There's more...
Performing CRUD operations using JDBC
Getting ready
How to do it...
There's more...
Using the Hikari Connection Pool (HikariCP)
Getting ready
How to do it...
How it works...
There's more...
Using prepared statements
Getting ready
How to do it...
There's more...
Using transactions
Getting ready
How to do it...
There's more...
Working with large objects
Getting ready
How to do it...
There's more...
Executing stored procedures
Getting ready
How to do it...
There's more...
Using batch operations for a large set of data
Getting ready
How to do it...
How it works...
There's more...
Using MyBatis for CRUD operations
Getting ready
How to do it...
How it works...
There's more...
Using the Java Persistence API and Hibernate
Getting ready
How to do it...
How it works...
Concurrent and Multithreaded Programming
Introduction
Using the basic element of concurrency – thread
Getting ready
How to do it...
There's more...
Different synchronization approaches
Getting ready
How to do it...
There's more...
Immutability as a means of achieving concurrency
Getting ready
How to do it...
There's more...
Using concurrent collections
Getting ready
How to do it...
How it works...
Using the executor service to execute async tasks
Getting ready
How to do it...
How it works...
There's more...
Using fork/join to implement divide-and-conquer
Getting ready
How to do it...
Using flow to implement the publish-subscribe pattern
Getting ready
How to do it...
Better Management of the OS Process
Introduction
Spawning a new process
Getting ready
How to do it...
How it works...
Redirecting the process output and error streams to file
Getting ready
How to do it...
There's more...
Changing the working directory of a subprocess
Getting ready
How to do it...
How it works...
Setting the environment variable for a subprocess
How to do it...
How it works...
Running shell scripts
Getting ready
How to do it...
How it works...
Obtaining the process information of the current JVM
How to do it...
How it works...
Obtaining the process information of the spawned process
Getting ready
How to do it...
Managing the spawned process
How to do it...
Enumerating live processes in the system
How to do it...
Connecting multiple processes using pipe
Getting ready
How to do it...
How it works...
Managing subprocesses
Getting ready
How to do it...
How it works...
RESTful Web Services Using Spring Boot
Introduction
Creating a simple Spring Boot application
Getting ready
How to do it...
How it works...
Interacting with the database
Getting ready
Installing MySQL tools
Creating a sample database
Creating a person table
Populating sample data
How to do it...
How it works...
Creating a RESTful web service
Getting ready
How to do it...
How it works...
Creating multiple profiles for Spring Boot
Getting ready
How to do it...
How it works...
There's more...
Deploying RESTful web services to Heroku
Getting ready 
Setting up a Heroku account
Creating a new app from the UI
Creating a new app from the CLI
How to do it...
There's more...
Containerizing the RESTful web service using Docker
Getting ready
How to do it...
How it works...
Monitoring the Spring Boot 2 application using Micrometer and Prometheus
Getting ready
How to do it...
How it works...
There's more
Networking
Introduction
Making an HTTP GET request
How to do it...
How it works...
Making an HTTP POST request
How to do it...
Making an HTTP request for a protected resource
How to do it...
How it works...
Making an asynchronous HTTP request
How to do it...
Making an HTTP request using Apache HttpClient
Getting ready
How to do it...
There's more...
Making an HTTP request using the Unirest HTTP client library
Getting ready
How to do it...
There's more...
Memory Management and Debugging
Introduction
Understanding the G1 garbage collector
Getting ready
How to do it...
How it works...
Unified logging for JVM
Getting ready
How to do it...
Using the jcmd command for the JVM
How to do it...
How it works...
Try-with-resources for better resource handling
How to do it...
How it works...
Stack walking for improved debugging
Getting ready
How to do it...
How it works...
Using the memory-aware coding style
How to do it...
Best practices for better memory usage
How to do it...
Understanding Epsilon, a low-overhead garbage collector
How to do it...
The Read-Evaluate-Print Loop (REPL) Using JShell
Introduction
Getting familiar with REPL
Getting ready
How to do it...
How it works...
Navigating JShell and its commands
How to do it...
Evaluating code snippets
How to do it...
There's more...
Object-oriented programming in JShell
How to do it...
Saving and restoring the JShell command history
How to do it...
Using the JShell Java API
How to do it...
How it works...
Working with New Date and Time APIs
Introduction
How to work with time zone-independent date and time instances
Getting ready
How to do it…
How it works…
There's more…
How to construct time zone-dependent time instances
Getting ready
How to do it…
How it works…
There's more…
How to create a date-based period between date instances
Getting ready
How to do it…
How it works…
There's more…
How to create a time-based period between time instances
Getting ready
How to do it…
How it works…
There's more…
How to represent epoch time
Getting ready
How to do it…
How it works…
There's more…
How to manipulate date and time instances
Getting ready
How to do it… 
There's more…
How to compare date and time
Getting ready
How to do it…
There's more…
How to work with different calendar systems
Getting ready
How to do it…
How it works…
There's more…
How to format dates using the DateTimeFormatter
Getting ready
How to do it…
How it works…
Testing
Introduction
Behavioral testing using Cucumber
How to do it...
How it works...
Unit testing of an API using JUnit
Getting ready
How to do it...
How it works...
Unit testing by mocking dependencies
Getting ready
How to do it...
How it works...
There's more...
Using fixtures to populate data for testing
How to do it...
How it works...
Integration testing
Getting ready
How to do it...
How it works...
The New Way of Coding with Java 10 and Java 11
Introduction
Using local-variable type inference
Getting ready
How to do it...
Using local-variable syntax for lambda parameters
Getting ready
How to do it...
GUI Programming Using JavaFX
Introduction
Creating a GUI using JavaFX controls
Getting ready
How to do it...
How it works...
Using the FXML markup to create a GUI
Getting ready
How to do it...
How it works...
Using CSS to the style elements in JavaFX
Getting ready
How to do it...
How it works...
Creating a bar chart
Getting ready
How to do it...
How it works...
Creating a pie chart
Getting ready
How to do it...
How it works...
Embedding HTML in an application
Getting ready
How to do it...
How it works...
There's more...
Embedding media in an application
Getting ready
How to do it...
How it works...
There's more...
Adding effects to controls
Getting ready
How to do it...
How it works...
There's more...
Using the Robot API
Getting ready
How to do it...
How it works...
Other Books You May Enjoy
Leave a review - let other readers know what you think
This cookbook offers a range of software development examples that are illustrated by simple and straightforward code, providing step-by-step resources and time-saving methods to help you solve data problems efficiently. Starting with the installation of Java, each recipe addresses a specific problem and is accompanied by a discussion that explains the solution and offers insight into how it works. We cover major concepts about the core programming language, as well as common tasks involved in building a wide variety of software. You will follow recipes to learn about new features of the latest Java 11 release to make your application modular, secure, and fast.
The intended audience includes beginners, programmers with intermediate experience, and even experts; all will be able to access these recipes, which demonstrate the latest features released with Java 11.
Chapter 1, Installation and a Sneak Peek into Java 11, helps you to set up the development environment for running your Java programs and gives a brief overview of the new features and tools in Java 11.
Chapter 2, Fast Track to OOP – Classes and Interfaces, covers Object-Oriented Programming (OOP) principles and design solutions, including inner classes, inheritance, composition, interfaces, enumerations, and the Java 9 changes to Javadocs.
Chapter 3, Modular Programming, introduces Jigsaw as a major feature and a huge leap for the Java ecosystem. This chapter demonstrates how to use tools, such as jdeps and jlink, to create simple modular applications and related artifacts, such as modular JARs, and finally, how to modularize your pre-Jigsaw applications.
Chapter 4, Going Functional, introduces a programming paradigm called functional programming. The topics covered include functional interfaces, lambda expressions, and lambda-friendly APIs.
Chapter 5, Streams and Pipelines, shows how to leverage streams and chain multiple operations on a collection to create a pipeline, use factory methods to create collection objects, create and operate on streams, and create an operation pipeline on streams, including parallel computations.
Chapter 6, Database Programming, covers both basic and commonly used interactions between a Java application and a database, right from connecting to the database and performing CRUD operations to creating transactions, storing procedures, and working with large objects.
Chapter 7, Concurrent and Multithreaded Programming, presents different ways of incorporating concurrency and some best practices, such as synchronization and immutability. The chapter also discusses the implementation of some commonly used patterns, such as divide-conquer and publish-subscribe, using the constructs provided by Java.
Chapter 8, Better Management of the OS Process, elaborates on the new API enhancements regarding the Process API.
Chapter 9, RESTful Web Services Using Spring Boot, deals with creating simple RESTful web services using Spring Boot, deploying them to Heroku, dockerizing Spring Boot-based RESTful web service applications, and monitoring Spring Boot applications using Prometheus.
Chapter 10, Networking, shows you how to use different HTTP client API libraries; namely, the new HTTP client API shipped with latest JDK, the Apache HTTP client, and the Unirest HTTP client API.
Chapter 11, Memory Management and Debugging, explores managing the memory of a Java application, including an introduction to the garbage collection algorithm used in Java 9, and some new features that help in advanced application diagnostics. We'll also show how to manage resources by using the new try-with-resources construct and the new stack-walking API.
Chapter 12, The Read-Evaluate-Print Loop (REPL) Using JShell, shows you how to work with the new REPL tool and JShell, provided as part of the JDK.
Chapter 13, Working with New Date and Time APIs, demonstrates how to construct time zone-dependent and independent date and time instances, how to create a date- and time-based period between date instance, how to represent epoch time, how to manipulate and compare date and time instances, how to work with different calendar systems, and how to format dates using the DateTimeFormatter.
Chapter 14, Testing, explains how to unit test your APIs before they are integrated with other components, including stubbing dependencies with some dummy data and mocking dependencies. We will also show you how to write fixtures to populate test data and then how to test your application behavior by integrating different APIs and testing them.
Chapter 15, The New Way of Coding with Java 10 and Java 11, demonstrates how to use local variable type inference and when and how to use local variable syntax for lambda parameters.
Chapter 16, GUI Programming Using JavaFX, explains how to use JavaFX for creating a GUI using FXML Markup, and CSS. It will demonstrate creating a bar chart, a pie chart, a line chart, an area chart. It will also show how to embed HTML in an application and a media source and how to add effects to controls. Also, we will learn about the newly released Robot API in the OpenJFX 11 update.
In order to get the most out of this book, some knowledge of Java and the ability to run Java programs is required. Also, it helps to have your favorite editor or, even better, an IDE installed and configured for use in the recipes. Because the book is essentially a collection of recipes, with each recipe being based on specific examples, the benefits of the book will be lost if the reader does not execute the examples provided. Readers will get even more from this book if they reproduce every example that is provided in their IDE, execute it, and compare their result with the one shown in the book.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.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.packt.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 athttps://github.com/PacktPublishing/Java-11-Cookbook-Second-Edition. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also). To give clear instructions on how to complete a recipe, use these sections as follows:
This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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.packt.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 packt.com.
In this chapter, we will cover the following recipes:
Installing JDK 18.9 on Windows and setting up the PATH variable
Installing JDK 18.9 on Linux (Ubuntu, x64) and configuring the PATH variable
Compiling and running a Java application
What's new in JDK 18.9
Using application class-data sharing
Every quest for learning a programming language begins with setting up the environment to experiment with our learning. Keeping in sync with this philosophy, in this chapter, we will show you how to set up your development environment and then run a simple modular application to test our installation. After that, we'll give you an introduction to the new features and tools in JDK 18.9. Then, we will compare JDK 9, 18.3, and 18.9. We'll end the chapter with a new feature introduced in JDK 18.3 that allows application-class-data sharing.
In this recipe, we will look at installing JDK on Windows and how to set up the PATH variable to be able to access the Java executables (such as javac, java, and jar) from anywhere within the command shell.
Visit
http://jdk.java.net/11/
and accept the early-adopter license agreement, which looks like this:
After accepting the license, you will get a grid of the available JDK bundles based on the OS and architecture (32/64-bit).
Click to download the relevant JDK executable (
.exe
) for your Windows platform.
Run the JDK executable (
.exe
) and follow the onscreen instructions to install JDK on your system.
If you have chosen all the defaults during the installation, you will find JDK installed in
C:/Program Files/Java
for 64 bit and
C:/Program Files (x86)/Java
for 32 bit.
Now that we have finished installing JDK, let's see how we can set the PATH variable.
The tools provided with JDK, namely javac, java, jconsole, and jlink, are available in the bin directory of your JDK installation. There are two ways you could run these tools from the Command Prompt:
Navigate to the directory where the tools are installed and run them, as follows:
cd "C:\Program Files\Java\jdk-11\bin" javac -version
Export the path to the directory so that the tools are available from any directory in the command prompt. To achieve this, we have to add the path to the JDK tools in the
PATH
environment variable. The command prompt will search for the relevant tool in all the locations declared in the
PATH
environment variable.
Let's see how you can add the JDK bin directory to the PATH variable:
Right-click on
My Computer
and then click on
Properties
. You will see your system information. Search for
Advanced system settings
and click on it to get a window, as shown in the following screenshot:
Click on
Environment Variables
to view the variables defined in your system. You will see that there are quite a few environment variables already defined, as shown in the following screenshot (the variables will differ across systems; in the following screenshot, there are a few predefined variables and a few variables added by me):
The variables defined under System variables are available across all the users of the system, and those defined under User variables for <user name> are available only to the specific user.
A new variable, with the name
JAVA_HOME
, and its value as the location of the JDK 9 installation. For example, it would be
C:\Program Files\Java\jdk-11
(for 64 bit) or
C:\Program Files (x86)\Java\jdk-11
(for 32 bit):
Update the
PATH
environment variable with the location of the bin directory of your JDK installation (defined in the
JAVA_HOME
environment variable). If you already see the
PATH
variable defined in the list, then you need to select that variable and click on
Edit
. If the
PATH
variable is not seen, click on
New
.
Any of the actions in the previous step will give you a popup, as shown in the following screenshot (on Windows 10):
The following screenshot shows the other Windows versions:
You can either click on
New
in the first screenshot and insert the
%JAVA_HOME%\bin
value, or you can append the value against the
Variable value
field by adding
; %JAVA_HOME%\bin
. The semicolon (
;
) in Windows is used to separate multiple values for a given variable name.
After setting the values, open the command prompt and run
javac -version
. You should be able to see
javac 11-ea
as the output. If you don't see it, it means that the bin directory of your JDK installation has not been correctly added to the
PATH
variable.
In this recipe, we will look at installing JDK on Linux (Ubuntu, x64), and how to configure the PATH variable to make the JDK tools (such as javac, java, and jar) available from any location within the Terminal.
Follow steps 1 and 2 of the
Installing JDK 18.9 on Windows and setting up the PATH variable
recipe to reach the downloads page.
Copy the download link (
tar.gz
) for the JDK for the Linux x64 platform from the downloads page.
Download the JDK by using
$> wget <copied link>
, for example,
$> wget https://download.java.net/java/early_access/jdk11/26/BCL/jdk-11-ea+26_linux-x64_bin.tar.gz
.
Once the download completes, you should have the relevant JDK available, for example,
jdk-11-ea+26_linux-x64_bin.tar.gz
. You can list the contents by using
$> tar -tf jdk-11-ea+26_linux-x64_bin.tar.gz
. You can even pipe it to
more
to paginate the output:
$> tar -tf jdk-11-ea+26_linux-x64_bin.tar.gz | more
.
Extract the contents of the
tar.gz
file under
/usr/lib
by using
$> tar -xvzf jdk-11-ea+26_linux-x64_bin.tar.gz -C /usr/lib
. This will extract the contents into a directory,
/usr/lib/jdk-11
. You can then list the contents of JDK 11 by using
$> ls /usr/lib/jdk-11
.
Update the
JAVA_HOME
and
PATH
variables by editing the
.bash_aliases
file in your Linux home directory:
$> vim ~/.bash_aliases export JAVA_HOME=/usr/lib/jdk-11 export PATH=$PATH:$JAVA_HOME/bin
Source the .bashrc file to apply the new aliases:
$> source ~/.bashrc $> echo $JAVA_HOME /usr/lib/jdk-11 $>javac -version javac 11-ea $> java -version java version "11-ea" 2018-09-25
Java(TM) SE Runtime Environment 18.9 (build 11-ea+22)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11-ea+22, mixed mode)
In this recipe, we will write a very simple modular Hello world program to test our JDK installation. This simple example prints Hello world in XML; after all, it's the world of web services.
You should have JDK installed and the PATH variable updated to point to the JDK installation.
The release of Java 9 was a milestone in the Java ecosystem. The modular framework developed under Project Jigsaw became part of Java SE release. Another major feature was the JShell tool, which is a REPL tool for Java. Many other new features introduced with Java 9 are listed in the release notes: http://www.oracle.com/technetwork/java/javase/9all-relnotes-3704433.html.
In this recipe, we will enumerate and discuss some of the new features introduced with JDK 18.3 and 18.9 (Java 10 and 11).
The Java 10 release (JDK 18.3) started a six-month release cycle—every March and every September—and a new release numbering system. It also introduced many new features, the most significant of which (for application developers) are the following:
Local variable type inference that allows the declaration of a variable using the reserved
var
type (see
Chapter 15
,
The New Way of Coding with Java 10 and Java 11
)
Parallel full garbage collection for the G1 garbage collector, which improves worst-case latencies
A new method,
Optional.orElseThrow()
, that is now the preferred alternative to the existing
get()
method
New APIs for
creating
unmodifiable collections: The
List.copyOf()
,
Set.copyOf()
, and
Map.copyOf()
methods of the
java.util
package and new methods of the
java.util.stream.Collectors
class:
toUnmodifiableList()
,
toUnmodifiableSet()
, and
toUnmodifiableMap()
(see
Chapter 5
,
Streams and Pipelines
)
A default set of root Certification Authorities, making OpenJDK builds more appealing to developers
A new Javadoc command-line option,
--add-stylesheet
, provides support for the use of multiple stylesheets in the generated documentation
Extending the existing class-data sharing feature to allow application classes to be placed in the shared archive that improves startup time and reduces the footprint (see the
Using application class-data sharing
recipe)
An experimental just-in-time compiler, Graal, can be used on the Linux/x64 platform
A clean garbage-collector (GC) interface that makes it simpler to add a new GC to HotSpot without perturbing the current code base and makes it easier to exclude a GC from a JDK build
Enabling HotSpot to allocate the object heap on an alternative memory device, such as an NVDIMM memory module, specified by the user
Thread-local handshakes, for executing a callback on threads without performing a global VM
safepoint
Docker awareness: JVM will know whether it is running in a Docker container on a Linux system and can extract container-specific configuration information instead of querying the operating system
Three new JVM options, to give Docker container users greater control over the system memory
See the full list of Java 10's new features in the release notes: https://www.oracle.com/technetwork/java/javase/10-relnote-issues-4108729.html.
We will discuss the new features of JDK 18.9 in more detail in the next section.
We have picked a few features that we feel are the most important and useful for an application developer.
Epsilon is a so-called no-op garbage collector that basically does nothing. Its use cases include testing for performance, memory pressure, and the virtual machine interface. It also could be used for short-lived jobs or the jobs that do not consume much memory and do not require garbage collection.
We discussed this feature in more details in the recipe Understand Epsilon, a low-overhead garbage collector recipe in Chapter 11, Memory Management and Debugging.
JDK 18.9 standardizes the incubated HTTP API client introduced in JDK 9 and updated in JDK 10. Based on CompleteableFuture, it supports nonblocking requests and responses. The new implementation is asynchronous and provides a better traceable data flow.
Chapter 10, Networking, explains this feature in more detail in several recipes.
A local-variable syntax for lambda parameters has the same syntax as a local-variable-declaration using the reserved var type introduced in Java 11. See the Using local variable syntax for lambda parameters recipe in Chapter 15, The New Way of Coding with Java 10 and Java 11, for more details.
The Z Garbage Collector (ZGC) is an experimental low-latency garbage collector. Its pause times should not exceed 10 ms and there should be no more than 15% application throughput reduction compared to using the G1 collector. ZGC also lays a foundation for future features and optimizations. Linux/x64 will be the first platform to get ZGC support.
There are quite a few other changes introduced in JDK 18.9:
The Java EE and CORBA modules are removed
JavaFX is separated and removed from the Java standard libraries
The Pack200 and Unpack200 tools and the Pack200 API in
util.jar
are deprecated
The Nashorn JavaScript engine, along with the JJS tool, are deprecated with the intent to remove them in the future
The Java class file format is extended to support a new constant pool form,
CONSTANT_Dynamic
Aarch64 intrinsics are improved, with the implementation of new intrinsics for the
java.lang.Math
sin, cos, and log functions, on Aarch64 processorsJEP 309—Dynamic Class-File Constants
Flight Recorder provides a low-overhead data-collection framework for troubleshooting both Java applications and the HotSpot JVM
The Java launcher can now run a program supplied as a single file of Java source code, so these programs can run directly from the source
A low-overhead heap profiling, providing a way to sample Java heap allocations, is accessible via JVM Tool Interface
Transport Layer Security
(
TLS
) 1.3 increases security and improves performance
Support of Unicode version 10.0 in the
java.lang.Character
,
java.lang.String
,
java.awt.font.NumericShaper
,
java.text.Bidi,
java.text.
BreakIterator
, and
java.text.
Normalizer
classes
Read the Java 11 (JDK 18.9) release notes for more details and other changes.
This feature has existed in Java since Java 5. It was extended in Java 9 as a commercial feature by allowing not only bootstrap classes but also application classes to be placed in the archive shared by JVMs. In Java 10, this feature became part of the open JDK. It decreases startup time and, when several JVMs are running on the same machine with the same application being deployed, reduces memory consumption.
The advantages of loading classes from the shared archive became possible for two reasons:
The classes stored in the archive are preprocessed, which means that the JVM memory mapping is stored in the archive too. It reduces the overhead of class-loading when a JVM instance starts.
The memory region can even be shared between the JVM instances running on the same computer, which reduces overall memory consumption by eliminating the need to replicate the same information in each instance.
The new JVM functionality allows us to create a list of classes to be shared, then use this list to create a shared archive, and use the shared archive to fast-load archived classes into memory.
By default, JVM can create an archive using the list of classes that comes with JDK. For example, run the following command:
java -Xshare:dump
It will create the shared archive as a classes.jsa file. On a Linux system, this file is placed in the following folder:
/Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home/lib/server
C:\Program Files\Java\jdk-11\bin\server
If this folder is accessible by the system admin only, run the command as an admin.
Please notice that not all classes can be shared. For example, the .class files located in the directory on the classpath and classes loaded by custom class loaders cannot be added to the shared archive.
To tell the JVM to use the default shared archive, use the following command:
java -Xshare:on -jar app.jar
The preceding command maps the content of the archive at a fixed address. This memory-mapping operation may occasionally fail when the required address space is not available. If that happens when the -Xshare:on option is used, the JVM exits with an error. Alternatively, the -Xshare:auto option can be used, which just disables the feature and loads the classes from the classpath if the shared archive cannot be used for whatever reason.
The simplest way to create a list of loaded application classes is by using the following command:
java -XX:+UseAppCDS -XX:DumpLoadedClassList=classes.txt -jar app.jar
The preceding command records all the loaded classes in the classes.txt file. If you would like to make your application load faster, stop the JVM just after the application has been started. If you need it to load certain classes faster but these classes are not loaded at the application startup automatically, make sure that the use cases that require these classes are executed.
Alternatively, you can manually edit the
classes.txt
file and add/remove any classes you need to put in the shared archive. Create this file once automatically and see the format. It is a simple text file that lists one class in each line.
Once the list is created, use the following command to generate the shared archive:
java -XX:+UseAppCDS -Xshare:dump -XX:SharedClassListFile=classes.txt -XX:SharedArchiveFile=app-shared.jsa --class-path app.jar
Notice that the shared archive file has a name other than classes.jsa, so the default shared archive is not overwritten.
Use the created archive by executing the following command:
java -XX:+UseAppCDS -Xshare:on -XX:SharedArchiveFile=app-shared.jsa -jar app.jar
Again, you can use the -Xshare:auto option to avoid an unexpected exit of the JVM.
The effect of the shared archive usage depends on the number of classes in it and other particulars of the application. So, we recommend you experiment and test various configurations before committing to a certain list of classes in production.
In this chapter, we will cover the following recipes:
Implementing
Object-Oriented Design
(
OOD
)
Using inner classes
Using inheritance and aggregation
Coding to an interface
Creating interfaces with default and static methods
Creating interfaces with private methods
A better way to work with nulls using
Optional
Using the utility class
Objects
The recipes in this chapter do not require any prior knowledge of OOD. However, some experience of writing code in Java would be beneficial. The code samples in this chapter are fully functional and compatible with Java 11. For better understanding, we recommend that you try to run the presented examples.
We also encourage you to adapt the tips and recommendations in this chapter to your needs in the context of your team experience. Consider sharing your newfound knowledge with your colleagues and discuss how the described principles can be applied to your domain and your current project.
This chapter gives you a quick introduction to the concepts of object-oriented programming (OOP) and covers some enhancements that have been introduced since Java 8. We will also try to cover a few good OOD practices wherever applicable and demonstrate them using specific code examples.
One can spend many hours reading articles and practical advice on OOD in books and on the internet. Doing this can be beneficial for some people. But, in our experience, the fastest way to get hold of OOD is to try its principles early in your own code. That is exactly the goal of this chapter—to give you a chance to see and use the OOD principles so that the formal definition makes sense immediately.
One of the main criteria of well-written code is the clarity of the intent. A well-motivated and clear design helps achieve this. The code is run by a computer, but it is maintained—read and modified—by humans. Keeping this in mind will assure the longevity of your code and perhaps even a few thanks and mentions with appreciation from those who have to deal with it later.
In this chapter, you will learn how to use the five basic OOP concepts:
Object/class
: Keeping data and methods together
Encapsulation
: Hiding data and/or methods
Inheritance
: Extending another class data and/or methods
Interface
: Hiding the implementation and coding for a type
Polymorphism
: Using the base class type reference that points to a child class object
If you search the internet, you may notice that many other concepts and additions to them, as well as all OOD principles, can be derived from the five concepts listed previously. This means that a solid understanding of them is a prerequisite to a successful design of an object-oriented system.
In this recipe, you will learn the first two OOP concepts—object/class and encapsulation. These concepts are at the foundation of OOD.
The term object usually refers to an entity that couples data and procedures that can be applied to this data. Neither data nor procedures are required, but one of them is—and, typically, both are—always present. The data is called object fields (or properties), while procedures are called methods. Field values describe the object's state. Methods describe the object's behavior. Every object has a type, which is defined by its class—the template used for the object's creation. An object is also said to be an instance of a class.
Encapsulation is achieved by using the public, protected, or private Java keywords, called access modifiers, in the declaration of the fields and methods. There is also a default level of encapsulation when no access modifier is specified.
