Title Page
Java 9 Programming By Example
Your guide to software development
Peter Verhas
BIRMINGHAM - MUMBAI
Java 9 Programming By Example
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 information presented. However, the information contained in
this book is sold without warranty, either express or implied. Neither the
author, nor Packt Publishing, and its dealers and distributors will be held
liable 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 and products mentioned in this book by the appropriate use
of capitals. However, Packt Publishing cannot guarantee the accuracy of this
information.
First published: April 2017
Production reference: 1240417
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78646-828-4
www.packtpub.com
Credits
Author
Copy Editors
Peter Verhas
Muktikant Garimella
Zainab Bootwala
Reviewer
Project Coordinator
Jeff Friesen
Ulhas Kambali
Commissioning Editor
Proofreader
Kunal Parikh
Safis Editing
Acquisition Editor
Indexer
Denim Pinto
Mariammal Chettiyar
Content Development Editor
Graphics
Nikhil Borkar
Abhinash Sahu
Technical Editor
Production Coordinator
Hussain Kanchwala
Melwyn Dsa
About the Author
Peter Verhas is a senior software engineer and software architect having
electrical engineering and economics background from TU Budapest (MsC)
and PTE Hungary (MBA), and also studied at TU Delft and TU Vienna. He
created his first programs in 1979, and since then he has authored several
open source programs. He has worked in several positions in the
telecommunications and finance industries and was the CIO of the Hungarian
start-up index.hu during its early days.
Peter works for EPAM Systems in Switzerland, participating in software
development projects at various customer sites, and he supports talent
acquisition by interviewing candidates, training programs for developers, and
internal mentoring programs.
You can follow Peter on Twitter at @verhas, LinkedIn, and GitHub, or read his
technical blog, Java Deep, at .
Acknowledgement is the section of a book that everybody ignores by turning
the pages. This time, this section is a bit different. I will mention a few people
and their roles in the making of this book but, at the same time, I will explain
why and how it is important to rely on people, being a software developer.
Doing professional work is not possible without having a life. It is quite
obvious if you take that literally, but it is just as true figuratively. If you do
not find the balance between your personal and professional life, you will
burn out and will not operate professionally. This is the place to mention my
family, my parents whom I am lucky to still have around, my wife, and my
already adult kids who never stopped believing in me being able to do this
work, who know more than well what a hypocrite I am, advocating personalprofessional life balance, and who continually pushed me closer to this
equilibrium point in life so that I could keep performing professionally.
For professional work, coworkers are almost as important as family support.
It is important that you support your colleagues as much as you ask them for
their support. You learn a lot from books and from experience, but you learn
the most from other people. Pay attention to senior developers. You can,
however, learn just as much from juniors. No matter how ace you are, from
time to time, a rookie may shed light on a topic. During the years, I learned a
lot from juniors who brought a fresh view to the table, asking shocking
questions that were absolutely valid. I cannot name each and every junior
who aided my work with fresh out-of-the-box thinking.
I can, and should, however, name some peer professionals who actively
participated in the creation of this book with their advice, discussions, and
suggestions.
I should certainly mention Károly Oláh who was very enthusiastic about my
project, and he represented, supported, and encouraged the idea inside
EPAM systems. He actively discussed with the upper management that the
support for writing a book well fits the innovation line and development of
the company, and the people who work together. Without the official support
from the company providing extra time for the task, I would not have been
able to create this book.
Good company attracts good people who are clever and also good to work
with. I had many discussions about the book, topics, and how to explain
certain aspects with my fellow EPAMers: Krisztián Sallai, Peter Fodor,
Sándor Szilágyi, Mantas Aleknavicius, Gábor Lénard, and many others.
I will separately mention István Attila Kovács from our Budapest office with
whom I discussed Chapter 5 in detail, and who gave me very valuable
feedback about the topic. If he does not know something about Java parallel
computing, then that something does not exist.
As a summary and takeaway for the patient reader who read this section till
the end, technology, knowledge, skills, and experience are extremely
important for being a professional Java 9 developer, but it is the people who
really matter.
About the Reviewer
Jeff Friesen is a freelance author and software developer who has taught
Java in the classroom and by writing numerous articles and books since the
late 1990s. He holds a Bachelor of Science degree in Computer Science and
Mathematics. Prior to freelancing, Jeff worked for telecommunications,
investment, and software development companies.
Jeff freelances as a Java author and software developer.
Jeff has written Java I/O, NIO and NIO.2 and Java Threads and the
Concurrency Utilities for Apress. Full details are available on his website (http
://javajeff.ca/cgi-bin/makepage.cgi?/books).
I thank Nitin Dasan for the opportunity to tech review this book. I also thank
Ulhas Kambali for assisting me with the tech review process.
www.PacktPub.com
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 files available? You can upgrade to the eBook version at www.P
acktPub.com and as a print book customer, you are entitled to a discount on the
eBook copy. Get in touch with us at for more details.
At www.PacktPub.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.
/>
Get the most in-demand software skills with Mapt. Mapt gives you full
access to all Packt books and video courses, as well as industry-leading tools
to help you plan your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our
editorial process. To help us improve, please leave us an honest review on
this book's Amazon page at />If you'd like to join our team of regular reviewers, you can e-mail us at
We award our regular reviewers with free eBooks
and videos in exchange for their valuable feedback. Help us be relentless in
improving our products!
Table of Contents
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1.
Getting Started with Java 9
Getting started with Java
Installing Java
Installation on Windows
Installation on MAC OS X
Installation on Linux
Setting JAVA_HOME
Executing jshell
Looking at the byte code
Packaging classes into a JAR file
Managing the running Java application
Using an IDE
NetBeans
Eclipse
IntelliJ
IDE services
IDE screen structure
Editing files
Managing projects
Build the code and run it
Debugging Java
Summary
2.
The First Real Java Program - Sorting Names
Getting started with sorting
Bubble sort
Getting started with project structure and build tools
Make
Ant
Installing Ant
Using Ant
Maven
Installing Maven
Using Maven
Gradle
Installing Gradle
Setting up the project with Maven
Coding the sort
Understanding the algorithm and language constructs
Blocks
Variables
Types
Arrays
Expressions
Loops
Conditional execution
Final variables
Classes
Inner, nested, local, and anonymous classes
Packages
Methods
Interfaces
Argument passing
Fields
Modifiers
Object initializers and constructors
Compiling and running the program
Summary
3.
Optimizing the Sort - Making Code Professional
The general sorting program
A brief overview of various sorting algorithms
Quick sort
Project structure and build tools
Maven dependency management
Code the sort
Creating the interfaces
Creating BubbleSort
Amending the interfaces
Architectural considerations
Creating unit tests
Adding JUnit as dependency
Writing the BubbleSortTest class
Good unit tests
A good unit test is readable
Unit tests are fast
Unit tests are deterministic
Assertions should be as simple as possible
Unit tests are isolated
Unit tests cover the code
Refactor the test
Collections with wrong elements
Handling exceptions
Generics
Test Driven Development
Implementing QuickSort
The partitioning class
Recursive sorting
Non-recursive sorting
Implementing the API class
Creating modules
Why modules are needed
What is a Java module
Summary
4.
Mastermind - Creating a Game
The Game
The model of the game
Java collections
Interface collection
Set
Hash functions
Method equals
Method hashCode
Implementing equals and hashCode
HashSet
EnumSet
LinkedHashSet
SortedSet
NavigableSet
TreeSet
List
LinkedList
ArrayList
Queue
Deque
Map
HashMap
IdentityHashMap
Dependency injection
Implementing the game
ColorManager
The class color
JavaDoc and code comments
Row
Table
Guesser
UniqueGuesser
GeneralGuesser
The Game class
Creating an integration test
Summary
5.
Extending the Game - Run Parallel, Run Faster
How to make Mastermind parallel
Refactoring
Processes
Threads
Fibers
java.lang.Thread
Pitfalls
Deadlocks
Race conditions
Overused locks
Starving
ExecutorService
ForkJoinPool
Variable access
The CPU heartbeat
Volatile variables
Synchronized block
Wait and notify
Lock
Condition
ReentrantLock
ReentrantReadWriteLock
Atomic classes
BlockingQueue
LinkedBlockingQueue
LinkedBlockingDeque
ArrayBlockingQueue
LinkedTransferQueue
IntervalGuesser
ParallelGamePlayer
Microbenchmarking
Summary
6.
Making Our Game Professional - Do it as a Webapp
Web and network
IP
TCP/IP
DNS
The HTTP protocol
HTTP methods
Status codes
HTTP/2.0
Cookies
Client server and web architecture
Writing servlets
Hello world servlet
Java Server Pages
HTML, CSS, and JavaScript
Mastermind servlet
Storing state
HTTP session
Storing state on the client
Dependency injection with Guice
The MastermindHandler class
Storing state on the server
The GameSessionSaver class
Running the Jetty web servlet
Logging
Configurability
Performance
Log frameworks
Java 9 logging
Logging practice
Other technologies
Summary
7.
Building a Commercial Web Application Using REST
The MyBusiness web shop
Sample business architecture
Microservices
Service interface design
JSON
REST
Model View Controller
Spring framework
Architecture of Spring
Spring core
Service classes
Compiling and running the application
Testing the application
Integration test
Application test
Servlet filters
Audit logging and AOP
Dynamic proxy-based AOP
Summary
8.
Extending Our E-Commerce Application
The MyBusiness ordering
Setting up the project
Order controller and DTOs
Consistency checker
Annotations
Annotation retention
Annotation target
Annotation parameters
Repeatable annotations
Annotation inheritance
@Documented annotations
JDK annotations
Using reflection
Getting annotations
Invoking methods
Setting fields
Functional programming in Java
Lambda
Streams
Functional interfaces
Method references
Scripting in Java 9
Summary
9.
Building an Accounting Application Using Reactive Programming
Reactive... what?
Reactive programming in a nutshell
Reactive systems
Responsive
Resilient
Elastic
Message-driven
Back-pressure
Reactive streams
Reactive programming in Java
Implementing inventory
Summary
10.
Finalizing Java Knowledge to a Professional Level
Java deep technologies
Java agent
Polyglot programming
Polyglot configuration
Polyglot scripting
Business DSL
Problems with polyglot
Annotation processing
Programming in the enterprise
Static code analysis
Source code version control
Software versioning
Code review
Knowledge base
Issue tracking
Testing
Types of tests
Test automation
Black box versus white box
Selecting libraries
Fit for the purpose
License
Documentation
Project alive
Maturity
Number of users
The "I like it" factor
Continuous integration and deployment
Release management
Code repository
Walking up the ladder
Summary
Preface
Java drastically changed with the introduction of Java 8, and this change has
been elevated to a whole new level with the new version, Java 9. Java has a
well-established past, being more than 20 years old, but at the same time, it is
new, functional, reactive, and sexy. This is a language that developers love,
and at the same time, it is the number one choice of developer language for
many enterprise projects.
It is probably more lucrative to learn Java now than ever before, starting with
Java 9. We encourage you to start your professional developer career by
learning Java 9, and we have done our best in this book to help you along this
road. We assembled the topics of the book so that it is easy to start, and you
can feel the things working and moving very soon. At the same time, we have
tried to reach very far, signaling the road ahead for a professional developer.
The sands of time kept moving, and I discovered functional programming.
I could very well see why writing side-effect-free code worked! I was
hooked and started playing with Scala, Clojure, and Erlang. Immutability was
the norm here.
However, I wondered how traditional algorithms would look in a functional
setting and started learning about it.
A data structure is never mutated in place. Instead, a new version of the data
structure is created. The strategy of copy and write with maximized sharing
was an intriguing one! All that careful synchronization is simply not needed!
The languages come equipped with garbage collection. So, if a version is not
needed anymore, runtime would take care of reclaiming the memory.
All in good time, though! Reading this book will help you see that we need
not sacrifice algorithmic performance while avoiding in-place mutation!
What this book covers
Getting Started with Java 9, gives you a jump start in Java, helping
you install it on your computer and run your first interactive programs using
the new Jshell.
Chapter 1,
The First Real Java Program - Sorting Names, teaches you how to
create a development project. This time, we will create program files and
compile the code.
Chapter 2,
Optimizing the Sort - Making Code Professional, develops the code
further so that the code is reusable and not only a toy.
Chapter 3,
Mastermind - Creating a Game, is when some fun starts. We
develop a game application that is interesting and not as trivial as it first
seems, but we will do it.
Chapter 4,
Extending the Game - Run Parallel, Run Faster, shows you how to
utilize the multi-processor capabilities of modern architecture. This is a very
important chapter that details technologies, that only a few developers truly
understand.
Chapter 5,
Making Our Game Professional - Do it as a Webapp, transforms the
user interface from command-line to web browser-based, delivering better
user experience.
Chapter 6,
Building a Commercial Web Application Using REST, takes you
through the development of an application that has the characteristics of
many commercial applications. We will use the standard REST protocol
which has gained ground in enterprise computing.
Chapter 7,
Extending Our E-Commerce Application, helps you develop the
application further utilizing modern language features such as scripting and
lambda expressions.
Chapter 8,
Building an Accounting Application Using Reactive Programming,
teaches you how to approach some problems using reactive programming.
Chapter 9,
Finalizing Java Knowledge to a Professional Level, gives a bird'seye view of developer topics that play an important role in the life of a Java
developer, and which will guide you further in working as a professional
developer.
Chapter 10,