1. Trang chủ
  2. » Công Nghệ Thông Tin

Java 9 building robust modular applications master advanced java features and implement them to build amazing projects

1,2K 227 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.155
Dung lượng 24,66 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Java 9: Building Robust Modular ApplicationsMaster advanced Java features and implement them to buildamazing projects A learning path in two sections BIRMINGHAM - MUMBAI... PacktPub.com

Trang 2

Java 9: Building Robust Modular Applications

Master advanced Java features and implement them to buildamazing projects

A learning path in two sections

BIRMINGHAM - MUMBAI

Trang 4

Java 9: Building Robust

Modular Applications

Copyright © 2018 Packt Publishing

All rights reserved No part of this learning path 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 learning path to ensure the accuracy

of the information presented However, the information contained in this learning path 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 learning path.

Packt Publishing has endeavored to provide trademark information about all of the

companies and products mentioned in this learning path by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information.

Authors: Dr Edward Lavieri, Peter Verhas, Jason Lee

Reviewer: Mandar Jog, Dionisios Petrakopoulos

Content Development Editor: Rohit Kumar Singh

Graphics: Jason Monteiro

Production Coordinator: ArvindKumar Gupta

Published on: April 2018

Trang 5

Mapt is an online digital library that gives you full access to over5,000 books and videos, as well as industry leading tools to helpyou plan your personal development and advance your career Formore information, please visit our website

Trang 6

Why subscribe?

Spend less time learning and more time coding with practicaleBooks and Videos from over 4,000 industry professionalsImprove your learning with Skill Plans built especially for youGet a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

Trang 7

Did you know that Packt offers eBook versions of every book

published, with PDF and ePub files available? You can upgrade tothe eBook version at www.PacktPub.com and as a print book customer,you are entitled to a discount on the eBook copy Get in touch with

us at service@packtpub.com for more details

At www.PacktPub.com, you can also read a collection of free technicalarticles, sign up for a range of free newsletters, and receive

exclusive discounts and offers on Packt books and eBooks

Trang 8

Table of Contents

Title Page - Courses

Copyright and Credits - Courses

Java 9: Building Robust Modular Applications

Packt Upsell - Courses

Why subscribe?

PacktPub.com

Preface

Who this learning path is for

What this learning path covers

To get the most out of this learning path

Download the example code files Conventions used

Breaking the monolith

Playing around with the Java Shell

Taking control of external processes

Boosting performance with G1

Measuring performance with JMH

Getting started with HTTP 2.0

Encompassing reactive programming

Expanding the wish list

Summary

2 Discovering Java 9

Improved Contended Locking [JEP 143]

Improvement goals Segmented code cache [JEP 197]

Memory allocation Smart Java compilation, phase two [JEP 199]

Resolving Lint and Doclint warnings [JEP 212]

Tiered attribution for javac [JEP 215]

Annotations pipeline 2.0 [JEP 217]

New version-string scheme [JEP 223]

Generating run-time compiler tests automatically [JEP 233]

Testing class-file attributes generated by Javac [JEP 235]

Storing interned strings in CDS archives [JEP 250]

The problem The solution Preparing JavaFX UI controls and CSS APIs for modularization [JEP 253] JavaFX overview

Implications for Java 9

Trang 9

Compact strings [JEP 254]

Pre-Java 9 status New with Java 9 Merging selected Xerces 2.11.0 updates into JAXP [JEP 255] Updating JavaFX/Media to newer version of GStreamer [JEP 257] HarfBuzz Font-Layout Engine [JEP 258]

HiDPI graphics on Windows and Linux [JEP 263]

Marlin graphics renderer [JEP 265]

Unicode 8.0.0 [JEP 267]

New in Unicode 8.0.0 Updated Classes in Java 9 Reserved stack areas for critical sections [JEP 270]

The pre-Java 9 situation New in Java 9

Dynamic linking of language-defined object models [JEP 276] Proof of concept

Additional tests for humongous objects in G1 [JEP 278]

Improving test-failure troubleshooting [JEP 279]

Environmental information Java process information Optimizing string concatenation [JEP 280]

HotSpot C++ unit-test framework [JEP 281]

Enabling GTK 3 on Linux [JEP 283]

New HotSpot build system [JEP 284]

Summary

3 Java 9 Language Enhancements

Working with variable handlers [JEP 193]

Working with the AtoMiC Toolkit Using the sun.misc.Unsafe class Eliding depreciation warnings on import statements [JEP 211] Milling Project Coin [JEP 213]

Using the @SafeVarargs annotation The try-with-resource statement Using the diamond operator Discontinuing use of the underscore Making use of private interface methods Processing import statements correctly [JEP 216]

Summary

4 Building Modular Applications with Java 9

A modular primer

Reviewing Java's platform module system [JEP-200]

Modularizing JDK source code [JEP-201]

Pre-Java 9 JDK source code organization Development tools

Deployment Internationalization Monitoring

Trang 10

RMI Security Troubleshooting Web services JavaFX tools Java runtime environment Source code

Libraries

C header files Database JDK source code reorganized Understanding modular run-time images [JEP-220] Runtime format adoption

Runtime image restructure Supporting common operations De-privileging JDK classes Preserving existing behaviors Getting to know the module system [JEP-261] Module paths

Access-control boundary violations Runtime

Modular Java application packaging [JEP-275] Advanced look at the Java Linker Java Packager options

JLink - The Java Linker [JEP-282]

Encapsulating most internal APIs [JEP-260] Summary

5 Migrating Applications to Java 9

Quick review of Project Jigsaw

Classpath The monolithic nature of the JDK How modules fit into the Java landscape

Base module Reliable configuration Strong encapsulation Migration planning

Testing a simple Java application Potential migration issues

The JRE Access to internal APIs Accessing internal JARs JAR URL depreciation Extension mechanism The JDK's modularization Advice from Oracle

Preparatory steps Getting the JDK 9 early access build

Trang 11

Running your program before recompiling Updating third-party libraries and tools Compiling your application

Pre-Java 9 -source and -target options Java 9 -source and -target options Running jdeps on your code

Breaking encapsulation The add-opens option The add-exports option The permit-illegal-access option Runtime image changes

Java version schema JDK and JRE layout What has been removed Updated garbage collection Deployment

JRE version selection Serialized applets JNLP update

Nested resources

FX XML extension JNLP file syntax Numeric version comparison Useful tools

Java environment - jEnv Maven

Obtaining the M2Eclipse IDE Summary

6 Experimenting with the Java Shell

What is JShell?

Getting Started with JShell

Practical uses of JShell

Feedback modes Creating a custom feedback mode Listing your assets

Editing in the JShell Modifying text Basic navigation Historical navigation Advanced editing commands Working with scripts

Start up scripts Loading scripts Saving scripts Advanced scripting with JShell Summary

7 Leveraging the New Default G1 Garbage Collector

Overview of garbage collection

Trang 12

Object life cycle Object creation Object mid-life Object destruction Garbage collection algorithms Mark and sweep

Concurrent mark sweep (CMS) garbage collection Serial garbage collection

Parallel garbage collection G1 garbage collection Garbage collection options Java methods relevant to garbage collection The System.gc() method

The finalize() method Pre-Java 9 garbage collection

Visualizing garbage collection Garbage collection upgrades in Java 8 Case study - Games written with Java Collecting garbage with the new Java platform

Default garbage collection Depreciated garbage collection combinations Unified garbage collection logging

Unified JVM logging (JEP-158) Tags

Levels Decorations Output Command-line options Unified GC logging (JEP-271) Garbage collection logging options The gc tag

Macros Additional considerations Persistent issues

Making objects eligible for garbage collection Summary

8 Microbenchmarking Applications with JMH

Microbenchmarking overview

Approach to using JMH Installing Java 9 and Eclipse with Java 9 support Hands-on experiment

Microbenchmarking with Maven

Benchmarking options

Modes Time units Techniques for avoiding microbenchmarking pitfalls

Power management

OS schedulers

Trang 13

Time sharing Eliminating dead-code and constant folding Run-to-run variance

Cache capacity Summary

9 Making Use of the ProcessHandle API

What are processes?

The new ProcessHandle interface

Getting the PID of the current process

Getting information about a process

Listing processes

Listing children Listing descendants Listing all processes Waiting for processes

Terminating processes

A small process controller application

Main class Parameters class The ParamsAndHandle class The ControlDaemon class Summary

10 Fine-Grained Stack Tracing

Overview of the Java Stack

The importance of stack information

Example - Restricting callers Example - Getting logger for caller Working with StackWalker

Getting an instance of StackWalker RETAIN_CLASS_REFERENCE SHOW_REFLECT_FRAMES SHOW_HIDDEN_FRAMES Final thoughts on enum constants Accessing classes

Walking methods StackFrame

Performance

Summary

11 New Tools and Tool Enhancements

The new HTTP client [JEP-110]

The HTTP client before Java 9 Java 9's new HTTP client New API limitations Simplified Doclet API [JEP-221]

The pre-Java 9 Doclet API API enums

Trang 14

API classes

API interfaces

Problems with the pre-existing Doclet API Java 9's Doclet API

Compiler tree API

Language model API

The AnnotatedConstruct interface The SourceVersion enum

The UnknownEntityException exception HTML5 Javadoc [JEP-224]

Javadoc search [JEP-225]

Introducing camel case search

Remove launch-time JRE version selection [JEP-231] Parser API for Nashorn [JEP-236]

Nashorn

Using Nashorn as a command-line tool Using Nashorn as an embedded interpreter EMCAScript

Parser API

Multi-release JAR files [JEP-238]

Identifying multi-release JAR files

Related JDK changes

Java-level JVM compiler interface [JEP-243]

BeanInfo annotations [JEP-256]

JavaBean

BeanProperty

SwingContainer

BeanInfo classes

TIFF image input/output [JEP-262]

Platform logging API and service [JEP-264]

The java.util.logging package

Logging in Java 9

XML Catalogs [JEP-268]

The OASIS XML Catalog standard

JAXP processors

XML Catalogs prior to Java 9

Java 9 platform changes

Convenience factory methods for collections [JEP-269] Using collections before Java 9

Using new collection literals

Platform-specific desktop features [JEP-272]

Enhanced method handles [JEP-274]

Reason for the enhancement

Lookup functions

Argument handling

Additional combinations

Enhanced deprecation [JEP-277]

What the @Deprecated annotation really means

Trang 15

Additional Concurrency Updates

Java concurrency Concurrency explained System configurations Java threads

Concurrency improvements CompletableFuture API enhancements Class details

Enhancements Spin-Wait Hints

Summary

13 Security Enhancements

Datagram Transport Layer Security

DTLS protocol version 1.0 DTLS protocol version 1.2 DTLS support in Java 9 Creating PKCS12 keystores

Keystore primer Java Keystore (JKS) Builder The CallbackHandlerProtection class The PasswordProtection class

The PrivateKeyEntry class The SecretKeyEntry class The TrustedCertificateEntry class PKCS12 default in Java 9

Improving security application performance

Security policy enforcement Permission evaluation The java.Security.CodeSource package Package checking algorithm

TLS application-layer protocol negotiation extension TLS ALPN extension

The javax.net.ssl package The java.net.ssl package extension Leveraging CPU instructions for GHASH and RSA

Hashing OCSP stapling for TLS

Trang 16

OCSP stapling primer Changes for the Java 9 platform DRBG-based SecureRandom implementations

Summary

14 Command Line Flags

Unified JVM Logging [JEP 158]

Command-line options Decorations

Levels Output Tags Compiler control [JEP 165]

Compilation modes C1 compilation mode C2 compilation mode Tiered compilation Compiler control in Java 9 Diagnostic commands [JEP 228]

Heap profiling agent [JEP 240]

Removing your JHAT [JEP 241]

JVM command-line flag argument validation [JEP 245] Compile for older platform versions [JEP 247] Summary

15 Best Practices In Java 9

Support for UTF-8

The ResourceBundle class The nested class Fields and constructors Methods

Changes in Java 9 Unicode 7.0.0

The java.lang package The java.text package Additional significance The Linux/AArch64 port

Multi-resolution Images

Common Locale Data Repository (CLDR)

Summary

16 Future Directions

Future Changes to the JDK

JDK changes targeted for Java 10 Repository consolidation Native-header tool removal JDK-related submitted proposals Parallelize the Full GC Phase in CMS REST APIs for JMX

Support heap allocation

Trang 17

JDK-related drafted proposals

Finalization promptness

Java memory model

Foreign Function Interfaces

Isolated methods

Reducing metaspace waste

Improving IPv6 support

Unboxed argument lists for method handles

Enhanced MandelblotSet demo using value types

Efficient array comparison intrinsics

Future changes to the Java Compiler

Policy for retiring javac -source and -target options

Pluggable static analyzers

Future Changes to the Java Virtual Machine

JVM-related submitted proposals

Container aware Java

Enable execution of Java methods on GPU

Epsilon GC - The arbitrarily low overhead garbage (non-) collec tor

JVM-related drafted proposals

Provide stable USDT probe points on JVM compiled methods

Concurrent monitor deflation

Provide a low-overhead way of sampling Java heap allocations Diagnostic Command Framework

Enhanced Class Redefinition

Enable NUMA mode by default when appropriate

Value objects

Align JVM Access Checks

Future Changes to JavaX

JMX specific annotations for registration of managed resources

Modernize the GTK3 Look and Feel Implementation

Ongoing Special Projects

Trang 18

2 Java 9 Programming Blueprints

17 Introduction

New features in Java 8

Lambdas Streams The new java.time package Default methods

New features in Java 9

Java Platform Module System/Project Jigsaw Process handling API

Concurrency changes REPL

Projects

Process Viewer/Manager Duplicate File Finder Date Calculator Social Media Aggregator Email filter

JavaFX photo management

A client/server note application Serverless Java

Android desktop synchronization client Getting started

Summary

18 Managing Processes in Java

Creating a project

Bootstrapping the application

Defining the user interface

Initializing the user interface

Building the library

Concurrent Java with a Future interface Modern database access with JPA

Building the command-line interface

Building the graphical user interface

Trang 19

Clock Instant LocalDate LocalTime LocalDateTime ZonedDateTime Back to our code

A brief interlude on testing Building the command-line interface

Plugins and extensions with the Service Provider Interface Resource handling with try-with-resources

Adding a network - Twitter

Registering as a Twitter developer Adding Twitter preferences to Sunago OAuth and logging on to Twitter Adding a model for Twitter Implementing a Twitter client

A brief look at internationalization and localization Making our JAR file fat

Adding a refresh button Adding another network - Instagram

Registering as an Instagram developer Implementing the Instagram client Loading our plugins in Sunago Summary

22 Sunago - An Android Port

Getting started

Building the user interface

Android data access Android services Android tabs and fragments Summary

23 Email and Spam Management with MailFilter

Getting started

A brief look at the history of email protocols

JavaMail, the Standard Java API for Email

Trang 20

Building the CLI Building the GUI Building the service Summary

24 Photo Management with PhotoBeans

Getting started

Bootstrapping the project

Branding your application NetBeans modules

TopComponent - the class for tabs and windows Nodes, a NetBeans presentation object

Lookup, a NetBeans fundamental

Writing our own nodes

Adding a secondary panel Loading and saving preferences Reacting to changes in preferences Summary

25 Taking Notes with Monumentum

26 Serverless Java

Getting started

Planning the application

Building your first function

DynamoDB Simple Email Service Simple Notification Service Deploying the function Creating a role Creating a topic Deploying the function Testing the function

Trang 21

Configuring your AWS credentials Summary

27 DeskDroid - A Desktop Client for Your Android Phone

Getting started

Creating the Android project

Requesting permissions Creating the service Server-sent events

Controlling the service state Adding endpoints to the server Getting conversations Sending an SMS message Creating the desktop application

Defining the user interface Defining user interface behavior Sending messages

Getting updates Security

Securing the endpoints Handling authorization requests Authorizing the client

Project Amber Local-Variable Type Inference Enhanced enums

Lambda leftovers Looking around

Ceylon Kotlin Summary

Bibliography

Trang 22

on future developments of the Java platform You will also workthrough projects from which you can draw usable examples as youwork to solve your own unique challenges.

Trang 23

Who this learning path is for

This learning path is for Java developers who are looking to move alevel up and learn how to build robust applications in the latestversion of Java

Trang 24

What this learning path

covers

Section 1, Mastering Java 9, gives an overview and explanation of

the new features introduced in Java 9 and the importance of thenew APIs and enhancements This module will improve your

productivity, making your applications faster By learning the bestpractices in Java, you will become the go-to person in your

organization for Java 9

Section 2, Java 9 Programming Blueprints, takes you through 10

comprehensive projects in the book that will showcase the variousfeatures of Java 9 It covers various libraries and frameworks inthese projects, and also introduces a few more frameworks thatcomplement and extend the Java SDK

Trang 25

To get the most out of this learning path

1 Some basic knowledge of Java would help

2 Familiarity with more advanced topics, such as networkprogramming and threads, would be helpful, but is notassumed

Trang 26

Download the example code files

You can download the example code files for this learning pathfrom your account at www.packtpub.com If you purchased this learningpath elsewhere, you can visit www.packtpub.com/support and register tohave the files emailed directly to you

You can download the code files by following these steps:

1 Log in or register at www.packtpub.com

2 Select the SUPPORT tab

3 Click on Code Downloads & Errata

4 Enter the name of the learning path in the Search box andfollow the onscreen instructions

Once the file is downloaded, please make sure that you unzip orextract 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://gith ub.com/PacktPublishing/Java-9-Building-Robust-Modular-Applications/ We also haveother code bundles from our rich catalog of books and videos

available at https://github.com/PacktPublishing/ Check them out!

Trang 27

Conventions used

There are a number of text conventions used throughout this book

CodeInText: Indicates code words in text, database table names, foldernames, filenames, file extensions, pathnames, dummy URLs, userinput, and Twitter handles Here is an example: "Mount the

downloaded WebStorm-10*.dmg disk image file as another disk in yoursystem."

A block of code is set as follows:

Bold: Indicates a new term, an important word, or words that you

see onscreen For example, words in menus or dialog boxes appear

in the text like this Here is an example: "Select System info fromthe Administration panel."

Warnings or important notes appear like this.

Tips and tricks appear like this.

Trang 28

Get in touch

Feedback from our readers is always welcome

General feedback: Email feedback@packtpub.com and mention the

learning path title in the subject of your message If you have

questions about any aspect of this learning path, please email us atquestions@packtpub.com

Errata: Although we have taken every care to ensure the accuracy

of our content, mistakes do happen If you have found a mistake inthis learning path, we would be grateful if you would report this to

us Please visit www.packtpub.com/submit-errata, selecting your learningpath, clicking on the Errata Submission Form link, and entering thedetails

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 uswith the location address or website name Please contact us atcopyright@packtpub.com 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 eitherwriting or contributing to a book, please visit authors.packtpub.com

Trang 29

Please leave a review Once you have read and used this learningpath, why not leave a review on the site that you purchased itfrom? Potential readers can then see and use your unbiased

opinion to make purchase decisions, we at Packt can understandwhat you think about our products, and our authors can see yourfeedback on their book Thank you!

For more information about Packt, please visit packtpub.com

Trang 30

Mastering Java 9

Write reactive, modular, concurrent, and secure code

Trang 31

The Java 9 Landscape

Java is already a fully-grown adult in its own right more than twodecades since its first release With a stunning community of

developers and wide adoption in a number of industries, the

platform continues to evolve and keep up with the rest of the world

in terms of performance, security, and scalability We will beginour journey by exploring the most significant features introduced

in Java 9, what are the biggest drivers behind them, and what more

we can expect in subsequent developments of the platform, alongwith some of the things that did not make it in this release

In this chapter, we will cover the following topics:

Java 9 at 20,000 feet

Breaking the monolith

Playing around with the Java Shell

Taking control of external processes

Boosting performance with G1

Measuring performance with JMH

Getting ready for HTTP 2.0

Encompassing reactive programming

Expanding the wish list

Trang 32

Java 9 at 20,000 feet

You might be asking yourself isn't Java 9 just a maintenance

release with a set of features that did not make it into Java 8?

There is plenty of new stuff in Java 9 that makes it a distinct

version in its own right

Inarguably, the modularization of the Java platform (developed aspart of project Jigsaw) is the biggest piece of work that makes itsuccessfully in Java 9 Initially planned for Java 8, but postponed,project Jigsaw is also one of the main reasons why the final release

of Java 9 was further postponed Jigsaw also introduces a few

notable changes to the Java platform and is one of the reasons Java

9 is considered a major release We will explore these features indetail in the subsequent chapters

The JCP (Java Community Process) provides the mechanisms

to turn a set of feature proposals (also known as Java

Enhancement Proposals or JEPs) into formal specifications

that provide the basis to extend the platform with new

functionality Java 9 is no different in that regard Apart from theJigsaw-related Java enhancement proposals, there is a long list ofother enhancements that made it in Java 9 Throughout this book,

we will discuss the various features in terms of logical groups

based on the corresponding enhancement proposals, including thefollowing:

The Java Shell (also called JShell) an interactive shell for

the Java platform

New APIs to work with operating system processes in a

portable manner

The Garbage-first (G1) garbage collector introduced in Java

7 is made the default garbage collector in Java 9

Adding the Java Microbenchmark Harness (JMH) tool

that can be used to run performance benchmarks against Javaapplications is included as part of the Java distribution

Support for the HTTP 2.0 and WebSocket standards by means

of a new client API

Concurrency enhancements among which is the definition ofthe Flow class, which describes an interface for the reactive

streams specification in the Java platform

Some of the initial proposals that were accepted for release 9 did

Trang 33

not make it there and were postponed for a later release, along withother interesting things that developers may expect in the future.You can download the JDK 9 distribution for your system from http: //www.oracle.com/technetwork/java/javase/downloads/index.html, if you are eager toget your hands dirty before trying to move through the other

chapters and experimenting with the newly introduced samplesand concepts

Trang 34

Breaking the monolith

Over the years, the utilities of the Java platform have continued toevolve and increase, making it one big monolith In order to makethe platform more suitable for embedded and mobile devices, thepublication of stripped down editions such as Java CDC and Java

ME was necessary These, however, did not prove to be flexibleenough for modern applications with varying requirements in

terms of functionality provided by the JDK In that regard, the needfor a modular system came in as a viral requirement, not only toaddress modularization of the Java utilities (overall, more than

5000 Java classes and 1500 C++ source files with more than

25,0000 lines of code for the Hotspot runtime), but also to provide

a mechanism for developers to create and manage modular

applications using the same module system used in the JDK Java

8 provided an intermediate mechanism to enable applications touse only a subset of the APIs provided by the entire JDK, and thatmechanism was named compact profiles In fact, compact profilesalso provided the basis for further work that had to be done in

order to break dependencies between the various distinct

components of the JDK required to enable implementation of amodule system in Java

The module system itself has been developed under the name ofproject Jigsaw on the basis of which several Java enhancementproposals and a target JSR (376) were formed Much was put inplace to address the requirements of project Jigsaw there was

evidence of concept implementation with more features proposedthan the ones that successfully made it into Java 9 Apart from

that, a complete restructuring of the JDK code base has been madealong with a complete reorganization of the JDK distributable

images

There was considerable controversy in the community as to

whether an existing and mature Java module system such as OSGishould be adopted as part of the JDK instead of providing a

completely new module system However, OSGI targets runtimebehavior such as the resolution of module dependencies,

installation, uninstallation, starting and stopping of modules (alsonamed bundles in terms of OSGI), custom module classloaders,and so on Project Jigsaw however targets a compile-time modulesystem where resolution of dependencies happen when the

Trang 35

application is compiled Moreover, installing and uninstalling amodule as part of the JDK eliminates the need to include it as adependency explicitly during compilation Furthermore, loading ofmodule classes is made possible through the existing hierarchy ofclassloaders (the bootstrap and the extension and system

classloaders), although, there was a possibility of using custommodule classloaders pretty much similar to the module

classloaders of OSGI The latter was, however, abandoned; we willdiscuss Java module classloading in more detail when we talk

about the details of the module system in Java

Additional benefits from the Java module system include enhancedsecurity and performance By modularizing the JDK and

applications into Jigsaw modules, we are able to create

well-defined boundaries between components and their correspondingdomains This separation of concerns aligns with the security

architecture of the platform and is an enabler of better resourceutilization We have dedicated two detailed chapters to all of thepreceding points, and to the topic of adopting Java 9 as well, whichalso requires a degree of understanding on the possible approaches

to migrating existing projects to Java 9

Trang 36

Discovering Java 9

Java 9 represents a major release and consists of a large number ofinternal changes to the Java platform Collectively, these internalchanges represent a tremendous set of new possibilities for Javadevelopers, some stemming from developer requests, others fromOracle-inspired enhancements In this chapter, we will review 26 of

the most important changes Each change is related to a JDK

Enhancement Proposal (JEP) JEPs are indexed and housed at

openjdk.java.net/jeps/0 You can visit this site for additional information

on each JEP

The JEP program is part of Oracle's support for open source, open

innovation, and open standards While other open source Java projects can be found, OpenJDK is the only one supported by Oracle.

In this chapter, we will cover changes to the Java platform Thesechanges have several impressive implications, including:

Heap space efficiencies

Memory allocation

Compilation process improvements

Type testing

Annotations

Automated runtime compiler tests

Improved garbage collection

Trang 37

Playing around with the Java Shell

For a long time, there has been no standard shell shipped with theJava programming language to experiment with new language

features or libraries or for rapid prototyping If you wanted to dothis, you could write a test application with a main method,

compile it with javac, and run it This could be done either at thecommand line or using a Java IDE; however, in both cases, this isnot as convenient as having an interactive shell for the purpose

Starting an interactive shell in JDK 9 is as simple as running thefollowing command (assuming the bin directory of your JDK 9

installation is in the current path):

jshell

You may find it somewhat puzzling that an interactive shell has notbeen introduced earlier in the Java platform as many programminglanguages, such as Python, Ruby, and a number of others, alreadycome with an interactive shell in their earliest versions; However,this had still not made it on the priority features list for the earlierJava releases, until now, and it is out there and ready for use TheJava shell makes use of a JShell API that provides capabilities toenable autocompletion or evaluation of expressions and code

snippets, among other features A full chapter is dedicated to

discussing the details of the Java shell so that developers can makethe best use out of it

Trang 38

Taking control of external

processes

Up to JDK 9, if you wanted to create a Java process and handleprocess input/output, you had to use either the Runtime.getRuntime.exec()method, which allows us to execute a command in a separate OSprocess and get a java.lang.Process instance over which to provide

certain operations in order to manage the external process, or usethe new java.lang.ProcessBuilder class with some more enhancements inregard to interacting with the external process and also create ajava.lang.Process instance to represent the external process Both

mechanisms were inflexible and also non-portable as the set ofcommands executed by the external processes were highly

dependent on the operating system (additional effort had to beexerted in order to make the particular process operations portableacross multiple operating systems) A chapter is dedicated to thenew process API, providing developers with the knowledge of

creating and managing external processes in a much easier way

Trang 39

Boosting performance with G1

The G1 garbage collector was already introduced in JDK 7 and isnow enabled by default in JDK 9 It is targeted for systems withmultiple processing cores and a lot of available memory What arethe benefits of the G1 compared to previous types of garbage

collectors? How does it achieve these improvements? Is there aneed to manually tune it, and in what scenarios? These, and severalmore questions regarding G1, will be discussed in a separate

chapter

Trang 40

Measuring performance with JMH

On many occasions, Java applications may suffer from

performance degradation Exacerbating the issue is a lack of

performance tests that can provide at least a minimal set of

guarantees that performance requirements are met and, moreover,the performance of certain features will not degrade over time.Measuring performance of Java applications is not trivial,

especially due to the fact that there is a number of compiler andruntime optimizations that may affect performance statistics Forthat reason, additional measures such as warm-up phases and

other tricks must be used in order to provide more accurate

performance measurements The Java Microbenchmark Harness is

a framework that incorporates a number of techniques along with aconvenient API that can be used for this purpose It is not a newtool, but is included with the distribution of Java 9 If you have notadded JMH to your toolbox yet, read the detailed chapter on theusage of JMH in the context of Java 9 application development

Ngày đăng: 02/03/2019, 10:42

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN