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

Mastering java 9 write reactive, modular, concurrent, and secure code

599 210 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 599
Dung lượng 17,22 MB

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

Nội dung

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 organizatio

Trang 2

Mastering Java 9

Write reactive, modular, concurrent, and secure code

Trang 3

Dr Edward Lavieri

Peter Verhas

BIRMINGHAM - MUMBAI

Trang 5

Mastering Java 9

Copyright © 2017 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 informationpresented However, the information contained in this book is sold without warranty, either express

or implied Neither the authors, nor Packt Publishing, and its dealers and distributors will be heldliable for any damages caused or alleged to be caused directly or indirectly by this book

Packt Publishing has endeavored to provide trademark information about all of the companies andproducts mentioned in this book by the appropriate use of capitals However, Packt Publishing cannotguarantee the accuracy of this information

First published: October 2017

Trang 8

About the Authors

Dr Edward Lavieri is a veteran developer with a strong academic background He earned a

doctorate in computer science from Colorado Technical University, an MS in management

information systems (Bowie State University), an MS in education (Capella University), and an MS

in operations management (University of Arkansas)

He has been creating and teaching computer science courses since 2002 Edward retired from theU.S Navy as a Command Master Chief after 25 years of service As the founder and creative director

of three19, a software design and development studio, Edward is constantly designing and developingsoftware He uses a variety of game engines and development tools His passions include developingadaptive learning systems, educational games, and mobile apps

Edward has authored Adaptive Learning for Educational Game Design (CreateSpace), Getting

Started with Unity 5 (Packt), Learning AWS Lumberyard Game Development (Packt), LiveCode Mobile Development HOTSHOT (Packt), LiveCode Mobile Development Cookbook (Packt), and Software Consulting: A Revolutionary Approach (CreateSpace) He was the technical editor for Excel Formulas and Functions for Dummies (Wiley Publishing) He has also developed numerous

college courses involving computer science, information systems, and game development

Peter Verhas is a senior developer and software system architect with more than 30 years of

software development experience He currently works for EPAM as a senior developer, where he isinvolved in many customer projects and actively participates in the education activities of the

company Peter writes a technical blog and is committed to open source software development Hehas been using Java since 2005 and is also an author at Java Code Geeks

Trang 9

About the Reviewer

Mandar Jog is an expert IT trainer with over 15 years of training experience He is an expert in

technologies such as Java, J2EE, and Android He also holds SCJP and SCWCD certifications He is

an occasional blogger where he makes the readers feel "I can" for the complex concepts in Java andJ2EE He is a regular speaker at many engineering colleges for technical seminars and workshops

He was also the technical reviewer of the book, Modular Programming in Java 9 by Packt.

Thanks a lot Tejaswini, you have been my inspiration throughout this journey I am equally

grateful to my son, Ojas; his lovely smiles have always made me push myself further.

Trang 10

For support files and downloads related to your book, please visit www.PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub filesavailable? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, youare entitled to a discount on the eBook copy Get in touch with us at service@packtpub.com for more

Trang 12

Customer Feedback

Thanks for purchasing this Packt book At Packt, quality is at the heart of our editorial process Tohelp us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com /dp/1786468735

If you'd like to join our team of regular reviewers, you can e-mail us at customerreviews@packtpub.com Weaward our regular reviewers with free eBooks and videos in exchange for their valuable feedback.Help us be relentless in improving our products!

Trang 13

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

1 The Java 9 Landscape

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 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 Compact strings [JEP 254]

Pre-Java 9 status New with Java 9 Merging selected Xerces 2.11.0 updates into JAXP [JEP 255]

Trang 14

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

RMI Security Troubleshooting Web services

Trang 15

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 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

Trang 16

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

Object life cycle Object creation Object mid-life Object destruction Garbage collection algorithms

Trang 17

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 Time sharing Eliminating dead-code and constant folding Run-to-run variance

Cache capacity Summary

Trang 18

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

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

Compiler tree API Language model API

Trang 19

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

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 Summary

12 Concurrency and Reactive Programming

Trang 20

The Flow.Subscriber interface The Flow.Subscription interface The Flow.Processor interface Sample implementation

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

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

Summary

14 Command Line Flags

Unified JVM Logging [JEP 158]

Trang 21

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 JDK-related drafted proposals Finalization promptness Java memory model Foreign Function Interfaces Isolated methods

Reducing metaspace waste

Trang 22

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-) collector 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 23

The book gives an overview and explanation of the new features introduced in Java 9 and the

importance of the new APIs and enhancements Some of the new features of Java 9 are

groundbreaking, and if you are an experienced programmer, you will be able to make your enterpriseapplication leaner by implementing these new features You will be provided with practical guidance

in applying the newly acquired knowledge in regards to Java 9 and further information on future

developments of the Java platform This book will improve your productivity, making your

applications faster By learning the best practices in Java, you will become the go-to person in your

organization for Java 9

By the end of this book, you will not only know the important concepts of Java 9 but you will alsohave a nuanced understanding of the important aspects of programming with this great language

Trang 24

What this book covers

Chapter 1, The Java 9 Landscape, explores the most significant features introduced in Java 9, including

Project Jigsaw, the Java Shell, G1 garbage collection, and reactive programming This chapter

provides introductions to these topics, priming them for deeper coverage in the subsequent chapters

Chapter 2, Discovering Java 9, covers several changes to the Java platform to include heap space

efficiencies, memory allocation, compilation process improvements, type testing, annotations,

automated runtime compiler tests, and improved garbage collection

Chapter 3, Java 9 Language Enhancements, focuses on the changes made to the Java language These

changes impact variable handlers, depreciation warnings, improvements on Project Coin changesimplemented in Java 7, and import statement processing

Chapter 4, Building Modular Applications with Java 9, examines the structure of a Java module as

specified by Project Jigsaw and how Project Jigsaw was implemented as part of the Java platform.This chapter also reviews the key internal changes to the Java platform as they relate to the new

modular system

Chapter 5, Migrating Applications to Java 9, explores how to migrate Java 8 applications to the Java

9 platform Both manual and semi-automated migration processes are covered

Chapter 6, Experimenting with the Java Shell, covers JShell, the new command-line read-eval-print

loop tool in Java 9 Coverage includes information regarding the tool, the read-eval-print loop

concept, and the commands and command-line options for use with JShell

Chapter 7, Leveraging the New Default G1 Garbage Collector, takes an in-depth look at garbage

collection and how it is handled in Java 9

Chapter 8, Microbenchmarking Applications with JMH, examines how to write performance tests

using the Java Microbenchmark Harness (JMH), a Java harness library for writing benchmarks for theJava Virtual Machine (JVM) Maven is used along with JMH to help illustrate the power of

microbenchmarking with the new Java 9 platform

Chapter 9, Making Use of the ProcessHandle API, reviews new class APIs that enable the

management of operating system processes

Chapter 10, Fine-Grained Stack Tracing, covers the new API that permits an effective means of stack

walking The chapter includes detailed information on how to access stack trace information

Chapter 11, New Tools and Tool Enhancements, covers 16 Java Enhancement Proposals (JEPs) that

were incorporated into the Java 9 platform These JEPs cover a wide range of tools and updates toAPIs to make development with Java easier with greater optimization possibilities for our Java

applications

Trang 25

Chapter 12, Concurrency Enhancements, covers concurrency enhancements introduced with the Java 9

platform The primary focus is the support for reactive programming, a concurrency enhancement that

is provided by the Flow class API Additional concurrency enhancements introduced in Java 9 arealso covered

Chapter 13, Security Enhancements, covers several small changes made to the JDK that involve

security The security enhancements introduced with the Java 9 platform provide developers with agreater ability to write and maintain applications that are more secure than previously possible

Chapter 14, Command-Line Flags, explores the command-line flag changes in Java 9 Concepts

covered in this chapter include unified JVM logging, compiler control, diagnostic commands, profiling agent, JHAT, command-line flag argument validation, and compiling for older platformversions

heap-Chapter 15, Best Practices in Java 9, focuses on working with utilities provided by the Java 9 platform

to include UTF-8 property files, Unicode 7.0.0, Linux/AArch64 port, multiresolution images, andcommon locale data repository

Chapter 16, Future Directions, provides an overview of the future developments of the Java platform,

beyond Java 9 This includes a specific look at what is planned for Java 10 and what further changes

we are likely to see in the future

Trang 26

What you need for this book

To work with this text, you will need at least a basic knowledge of the Java programming language.You will also need the following software components:

Java SE Development Kit 9 (JDK)

Trang 27

Who this book is for

This book is for enterprise developers and existing Java developers Basic knowledge of Java isnecessary

Trang 28

In this book, you will find a number of text styles that distinguish between different kinds of

information Here are some examples of these styles and an explanation of their meaning

Code words in text, database table names, folder names, filenames, file extensions, pathnames,dummy URLs, and user input are shown as follows: "Under the subdirectory structure of C:\chapter8- benchmark\src\main\java\com\packt is the MyBenchmark.java file."

A block of code is set as follows:

public synchronized void protectedMethod()

{

}

New terms and important words are shown in bold.

Warnings or important notes appear like this.

Tips and tricks appear like this.

Trang 29

Reader feedback

Feedback from our readers is always welcome Let us know what you think about this book whatyou liked or disliked Reader feedback is important for us as it helps us develop titles that you willreally get the most out of

To send us general feedback, simply email feedback@packtpub.com, and mention the book's title in thesubject of your message

If there is a topic that you have expertise in and you are interested in either writing or contributing to

a book, see our author guide at www.packtpub.com/authors

Trang 30

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get themost from your purchase

Trang 31

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com Ifyou purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have thefiles e-mailed directly to you

You can download the code files by following these steps:

1 Log in or register to our website using your e-mail address and password

2 Hover the mouse pointer on the SUPPORT tab at the top

3 Click on Code Downloads & Errata

4 Enter the name of the book in the Search box

5 Select the book for which you're looking to download the code files

6 Choose from the drop-down menu where you purchased this book from

7 Click on Code Download

Once the file is downloaded, please make sure that you unzip or extract the folder using the latestversion 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/Mastering-Java -9 We also have other code bundles from our rich catalog of books and videos available at https://git hub.com/PacktPublishing/ Check them out!

Trang 32

Although we have taken every care to ensure the accuracy of our content, mistakes do happen If youfind a mistake in one of our books maybe a mistake in the text or the code we would be grateful ifyou could report this to us By doing so, you can save other readers from frustration and help us

improve subsequent versions of this book If you find any errata, please report them by visiting http:// www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, andentering the details of your errata Once your errata are verified, your submission will be acceptedand the errata will be uploaded to our website or added to any list of existing errata under the Erratasection of that title

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter thename of the book in the search field The required information will appear under the Errata section

Trang 33

Please contact us at copyright@packtpub.com with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content

Trang 34

If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and wewill do our best to address the problem

Trang 35

The Java 9 Landscape

Java is already a fully-grown adult in its own right more than two decades 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, andscalability We will begin our 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, along with 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 36

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 didnot make it into Java 8? There is plenty of new stuff in Java 9 that makes it a distinct version in itsown right

Inarguably, the modularization of the Java platform (developed as part of project Jigsaw) is the

biggest piece of work that makes it successfully 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 isconsidered a major release We will explore these features in detail 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 fromthe Jigsaw-related Java enhancement proposals, there is a long list of other 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 the following:

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 Java applications 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 of the Flow class, which describes aninterface for the reactive streams specification in the Java platform

Some of the initial proposals that were accepted for release 9 did not make it there and were

postponed for a later release, along with other interesting things that developers may expect in thefuture

You can download the JDK 9 distribution for your system from http://www.oracle.com/technetwork/java/java se/downloads/index.html, if you are eager to get your hands dirty before trying to move through the otherchapters and experimenting with the newly introduced samples and concepts

Trang 37

Breaking the monolith

Over the years, the utilities of the Java platform have continued to evolve and increase, making it onebig monolith In order to make the platform more suitable for embedded and mobile devices, the

publication of stripped down editions such as Java CDC and Java ME was necessary These,

however, did not prove to be flexible enough for modern applications with varying requirements interms of functionality provided by the JDK In that regard, the need for a modular system came in as aviral requirement, not only to address modularization of the Java utilities (overall, more than 5000Java 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 applicationsusing the same module system used in the JDK Java 8 provided an intermediate mechanism to enableapplications to use only a subset of the APIs provided by the entire JDK, and that mechanism wasnamed compact profiles In fact, compact profiles also 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 a module system in Java

The module system itself has been developed under the name of project Jigsaw on the basis of whichseveral Java enhancement proposals and a target JSR (376) were formed Much was put in place toaddress the requirements of project Jigsaw there was evidence of concept implementation with morefeatures proposed than the ones that successfully made it into Java 9 Apart from that, a completerestructuring of the JDK code base has been made along with a complete reorganization of the JDKdistributable images

There was considerable controversy in the community as to whether an existing and mature Java

module system such as OSGi should be adopted as part of the JDK instead of providing a completelynew module system However, OSGI targets runtime behavior such as the resolution of module

dependencies, installation, uninstallation, starting and stopping of modules (also named bundles interms of OSGI), custom module classloaders, and so on Project Jigsaw however targets a compile-time module system where resolution of dependencies happen when the application is compiled.Moreover, installing and uninstalling a module as part of the JDK eliminates the need to include it as

a dependency explicitly during compilation Furthermore, loading of module classes is made possiblethrough the existing hierarchy of classloaders (the bootstrap and the extension and system

classloaders), although, there was a possibility of using custom module classloaders pretty muchsimilar to the module classloaders of OSGI The latter was, however, abandoned; we will discussJava 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 enhanced security and performance Bymodularizing the JDK and applications into Jigsaw modules, we are able to create well-defined

boundaries between components and their corresponding domains This separation of concerns alignswith the security architecture of the platform and is an enabler of better resource utilization We havededicated two detailed chapters to all of the preceding points, and to the topic of adopting Java 9 aswell, which also requires a degree of understanding on the possible approaches to migrating existing

Trang 38

projects to Java 9.

Trang 39

Playing around with the Java Shell

For a long time, there has been no standard shell shipped with the Java programming language toexperiment with new language features or libraries or for rapid prototyping If you wanted to do this,you could write a test application with a main method, compile it with javac, and run it This could bedone either at the command line or using a Java IDE; however, in both cases, this is not as convenient

as having an interactive shell for the purpose

Starting an interactive shell in JDK 9 is as simple as running the following command (assuming thebin directory of your JDK 9 installation is in the current path):

jshell

You may find it somewhat puzzling that an interactive shell has not been introduced earlier in the Javaplatform as many programming languages, 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 thepriority features list for the earlier Java releases, until now, and it is out there and ready for use TheJava shell makes use of a JShell API that provides capabilities to enable autocompletion or

evaluation of expressions and code snippets, among other features A full chapter is dedicated todiscussing the details of the Java shell so that developers can make the best use out of it

Trang 40

Taking control of external processes

Up to JDK 9, if you wanted to create a Java process and handle process input/output, you had to useeither 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 use the new java.lang.ProcessBuilder class with some more

enhancements in regard to interacting with the external process and also create a java.lang.Process

instance to represent the external process Both mechanisms were inflexible and also non-portable asthe set of commands executed by the external processes were highly dependent on the operating

system (additional effort had to be exerted in order to make the particular process operations portableacross multiple operating systems) A chapter is dedicated to the new process API, providing

developers with the knowledge of creating and managing external processes in a much easier way

Ngày đăng: 02/03/2019, 11:18

TỪ KHÓA LIÊN QUAN