He is the author of the book, Java 7 Concurrency Cookbook and Mastering Concurrency Programming with Java 8 by Packt... The mechanisms are as follows: Basic thread management Thread sync
Trang 2Java 9 Concurrency Cookbook
Trang 3Java 9 Concurrency Cookbook
Second Edition
Copyright © 2017 Packt Publishing
All rights reserved No part of this book may be reproduced, stored in a retrieval system, ortransmitted in any form or by any means, without the prior written permission of thepublisher, 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 theinformation presented However, the information contained in this book is sold withoutwarranty, either express or implied Neither the author, nor Packt Publishing, and itsdealers and distributors will be held liable for any damages caused or alleged to be causeddirectly 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: October 2012
Second edition: April 2017
Trang 4Tejal Daruwale Soni
Content Development Editor
Trang 5About the Author
Javier Fernández González is a software architect with almost 15 years of experience
in Java technologies He has worked as a teacher, researcher, programmer, analyst, andwriter, and he now works as an architect in all types of projects related to Java, especiallyJ2EE As a teacher, has taken over 1,000 hours of training in basic Java, J2EE, and the Strutsframework As a researcher, he has worked in the field of information retrieval, developingapplications for processing large amounts of data in Java, and has participated as a
coauthor in several journal articles and conference presentations Recently, he worked ondeveloping J2EE web applications for various clients from different sectors (public
administration, insurance, healthcare, transportation, and so on) Currently, he works as a
software architect He is the author of the book, Java 7 Concurrency Cookbook and Mastering
Concurrency Programming with Java 8 by Packt.
Trang 6About the Reviewer
Piotr Bzdyl is focused on Java concurrency topics, including other JVM languages and theirlibraries, aimed at helping in creating highly concurrent applications (async IO, non-
blocking APIs, Scala, Akka, and Clojure) He has been helping teams with JVM tuning andtroubleshooting
He has also created a training course for Java concurrency topics, covering core JDK
multithreading concepts as well as those from external libraries and languages (actors, STM,parallel collections, and functional languages)
You can connect with Piotr on LinkedIn at h t t p s ://w w w l i n k e d i n c o m /i n /p i o t r b z d y l
and on GitHub at h t t p s ://g i t h u b c o m /p b z d y l You can follow him on Stack Overflow
at h t t p ://s t a c k o v e r f l o w c o m /c v /p i o t r e k b z d y l
Trang 7For 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 andePub files available? You can upgrade to the eBook version at www.PacktPub.comand as aprint 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 technical articles, sign up for arange of free newsletters and receive exclusive discounts and offers on Packt books andeBooks
h t t p s ://w w w p a c k t p u b c o m /m a p t
Get the most in-demand software skills with Mapt Mapt gives you full access to all Packtbooks and video courses, as well as industry-leading tools to help you plan your personaldevelopment 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
Trang 8Customer Feedback
Thanks for purchasing this Packt book At Packt, quality is at the heart of our editorialprocess To help us improve, please leave us an honest review on this book's Amazon page
at h t t p s ://w w w a m a z o n c o m /d p /178712441X
If you'd like to join our team of regular reviewers, you can e-mail us at
customerreviews@packtpub.com We award our regular reviewers with free eBooks andvideos in exchange for their valuable feedback Help us be relentless in improving ourproducts!
Trang 9To Nuria, Paula, and Pelayo, for you infinite love and patience
Trang 11Processing uncontrolled exceptions in a thread 32
Trang 13There's more 117
Trang 19Implementing the ThreadFactory interface to generate custom threads
Trang 25When you work with a computer, you can do several things at once You can listen to musicwhile you edit a document in a word processor and read your e-mails This can be donebecause your operating system allows the concurrency of tasks Concurrent programming
is about the elements and mechanisms a platform offers to have multiple tasks or programsrunning at once and communicating with each other, to exchange data or to synchronizewith each other Java is a concurrent platform, and it offers a lot of classes to execute
concurrent tasks inside a Java program With each version, Java increases the functionalitiesoffered to programmers to facilitate the development of concurrent programs This bookcovers the most important and useful mechanisms included in version 9 of the Java
concurrency API, so you will be able to use them directly in your applications The
mechanisms are as follows:
Basic thread management
Thread synchronization mechanisms
Thread creation and management delegation with executors
Fork/Join framework to enhance the performance of your application
Parallel streams to process big sets of data in a parallel way, including the newJava 9 reactive streams
Data structures for concurrent programs
Adapting the default behavior of some concurrency classes to your needs
Testing Java concurrency applications
What this book covers
Chapter 1, Thread Management, teaches you how to make basic operations with threads The
creation, execution, and status management of threads are explained through basic
examples
Chapter 2, Basic Thread Synchronization, covers how to use low-level Java mechanisms to
synchronize code Locks and the synchronized keyword are explained in detail
Chapter 3, Thread Synchronization Utilities, teaches how to use the high-level utilities of Java
to manage the synchronization between threads in Java It includes an explanation of how
to use the Phaser class to synchronize tasks divided into phases
Trang 26Chapter 4, Thread Executors, explores the delegation of thread management to executors.
They allow running, managing, and getting the results of concurrent tasks
Chapter 5, Fork/Join Framework, covers the use of the Fork/Join framework It’s a special
kind of executor oriented to execute tasks that will be divided into smaller ones using thedivide and conquer technique
Chapter 6, Parallel and Reactive Streams, teaches you how to create streams and use all its
intermediate and terminal operations to process big collections of data in a parallel andfunctional way Streams were introduced in Java 8 Java 9 has included some new interfaces
to implement reactive streams
Chapter 7, Concurrent Collections, explains how to use some concurrent data structures
provided by the Java language These data structures must be used in concurrent programs
to avoid the use of synchronized blocks of code in their implementation
Chapter 8, Customizing Concurrency Classes, teaches you how to adapt some of the most
useful classes of the Java concurrency API to your needs
Chapter 9, Testing Concurrent Applications, covers how to obtain information about the
status of some of the most useful structures of the Java 7 concurrency API You will alsolearn how to use some free tools to debug concurrent applications, such as the Eclipse,NetBeans IDE, or FindBugs applications to detect possible bugs in your applications
Chapter 10, Additional Information, explores the notions of synchronization, the executor,
the Fork/Join framework, concurrent data structures, and the monitoring of concurrentobjects, which were not included in the respective chapters
Chapter 11, Concurrent Programming Design, provides some tips that every programmer
should consider when they develop a concurrent application
What you need for this book
To follow this book, you need some basic knowledge of the Java programming language.You should know how to use an IDE, such as Eclipse or NetBeans, but this is not a
necessary prerequisite
Trang 27Who this book is for
If you are a Java developer interested in enhancing your knowledge of concurrent
programming and multithreading further, as well as discovering the new concurrency
features of Java 8 and Java 9, then the Java 9 Concurrency Cookbook is for you You should
already be comfortable with general Java development practices, and a basic grasp ofthreads would be an advantage
Sections
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, we use these sections as follows:
Getting ready
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
Trang 28In 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, user input, and Twitter handles are shown as follows: "The onethat executes the main() method."
A block of code is set as follows:
Thread task=new PrimeGenerator();
task.start();
New terms and important words are shown in bold Words that you see on the screen, for
example, in menus or dialog boxes, appear in the text like this: "Create a new project by
clicking on the New Project option under the File menu"
Warnings or important notes appear in a box like this
Tips and tricks appear like this
Reader feedback
Feedback from our readers is always welcome Let us know what you think about thisbook-what you liked or disliked Reader feedback is important for us as it helps us developtitles that you will really get the most out of
To send us general feedback, simply e-mail feedback@packtpub.com, and mention thebook's title in the subject of your message
If there is a topic that you have expertise in and you are interested in either writing orcontributing to a book, see our author guide at www.packtpub.com/authors
Trang 29Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase
Downloading the example code
You can download the example code files for this book from your account at h t t p ://w w w p
a c k t p u b c o m If you purchased this book elsewhere, you can visit h t t p ://w w w p a c k t p u b c
o m /s u p p o r tand register to have the files e-mailed directly to you
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password
You can also download the code files by clicking on the Code Files button on the book's
webpage at the Packt Publishing website This page can be accessed by entering the book's
name in the Search box Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using thelatest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at
https://github.com/PacktPublishing/Java-9-Concurrency-Cookbook-Second-Edition
We also have other code bundles from our rich catalog of books and videos available at h t t
p s ://g i t h u b c o m /P a c k t P u b l i s h i n g / Check them out!
Trang 30your book, clicking on the Errata Submission Form link, and entering the details of your
errata Once your errata are verified, your submission will be accepted and the errata will
be uploaded to our website or added to any list of existing errata under the Errata section ofthat title
To view the previously submitted errata, go to h t t p s ://w w w p a c k t p u b c o m /b o o k s /c o n t e n
t /s u p p o r tand enter the name of the book in the search field The required information will
appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media AtPackt, we take the protection of our copyright and licenses very seriously If you comeacross any illegal copies of our works in any form on the Internet, please provide us withthe location address or website name immediately so that we can pursue a remedy
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 valuablecontent
Questions
If you have a problem with any aspect of this book, you can contact us
at questions@packtpub.com, and we will do our best to address the problem
Trang 31Thread Management
In this chapter, we will cover the following topics:
Creating, running, and setting the characteristics of a thread
Interrupting a thread
Controlling the interruption of a thread
Sleeping and resuming a thread
Waiting for the finalization of a thread
Creating and running a daemon thread
Processing uncontrolled exceptions in a thread
Using thread local variables
Grouping threads and processing uncontrolled exceptions in a group of threadsCreating threads through a factory
Introduction
In the computer world, when we talk about concurrency, we refer to a series of independentand unrelated tasks that run simultaneously on a computer This simultaneity can be real ifthe computer has more than one processor or a multi-core processor, or it can be apparent ifthe computer has only one core processor
Trang 32All modern operating systems allow the execution of concurrent tasks You can read your mails while listening to music or reading news on a web page We can say this is process-level concurrency But inside a process, we can also have various simultaneous tasks.
e-Concurrent tasks that run inside a process are called threads Another concept related to
concurrency is parallelism There are different definitions and relations with the
concurrency concept Some authors talk about concurrency when you execute your
application with multiple threads in a single-core processor With this, you can see whenyour program execution is apparent They talk about parallelism when you execute yourapplication with multiple threads in a multi-core processor or in a computer with more thanone processor, so this case is real as well Other authors talk about concurrency when thethreads of an application are executed without a predefined order, and they discuss
parallelism when all these threads are executed in an ordered way
This chapter presents a number of recipes that will show you how to perform basic
operations with threads, using the Java 9 API You will see how to create and run threads in
a Java program, how to control their execution, process exceptions thrown by them, andhow to group some threads to manipulate them as a unit
Creating, running, and setting the
characteristics of a thread
In this recipe, we will learn how to do basic operations over a thread using the Java API Aswith every element in the Java language, threads are objects We have two ways of creating
a thread in Java:
Extending the Thread class and overriding the run() method
Building a class that implements the Runnable interface and the run() methodand then creating an object of the Thread class by passing the Runnable object as
a parameter this is the preferred approach and it gives you more flexibility
Trang 33In this recipe, we will use the second approach to create threads Then, we will learn how tochange some attributes of the threads The Thread class saves some information attributesthat can help us identify a thread, know its status, or control its priority These attributesare:
ID: This attribute stores a unique identifier for each thread.
Name: This attribute stores the name of the thread.
Priority: This attribute stores the priority of the Thread objects In Java 9, threads
can have priority between 1 and 10, where 1 is the lowest priority and 10 is thehighest It's not recommended that you change the priority of the threads It'sonly a hint to the underlying operating system and it doesn't guarantee anything,but it's a possibility that you can use if you want
Status: This attribute stores the status of a thread In Java, a thread can be present
in one of the six states defined in the Thread.State enumeration: NEW,
RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED The following
is a list specifying what each of these states means:
NEW: The thread has been created and it has not yet startedRUNNABLE: The thread is being executed in the JVMBLOCKED: The thread is blocked and it is waiting for a monitorWAITING: The thread is waiting for another thread
TIMED_WAITING: The thread is waiting for another thread with aspecified waiting time
TERMINATED: The thread has finished its execution
In this recipe, we will implement an example that will create and run 10 threads that wouldcalculate the prime numbers within the first 20,000 numbers
Getting ready
The example for this recipe has been implemented using the Eclipse IDE If you use Eclipse
or a different IDE, such as NetBeans, open it and create a new Java project
Trang 34How to do it
Follow these steps to implement the example:
Create a class named Calculator that implements the Runnable interface:1
public class Calculator implements Runnable {
Implement the run() method This method will execute the instructions of the2
thread we are creating, so this method will calculate the prime numbers withinthe first 20000 numbers:
Then, implement the auxiliar isPrime() method This method determines
3
whether a number is a prime number or not:
private boolean isPrime(long number) {
Trang 35Now implement the main class of the application Create a class named Main that4.
contains the main() method:
public class Main {
public static void main(String[] args) {
First, write some information regarding the values of the maximum, minimum,5
and default priority of the threads:
Thread threads[];
Thread.State status[];
threads = new Thread[10];
status = new Thread.State[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(new Calculator());
try (FileWriter file = new FileWriter(".\\data\\log.txt");
PrintWriter pw = new PrintWriter(file);) {
for (int i = 0; i < 10; i++) {
pw.println("Main : Status of Thread " + i + " : " +
threads[i].getState());
status[i] = threads[i].getState();
Trang 36for the finalization of a thread recipe of this chapter, we can use the join() method
to wait for this to happen In this case, we want to write information about thethreads when their statuses change, so we can't use this method We use thisblock of code:
boolean finish = false;
for (int i = 0; i < 10; i++) {
finish = finish && (threads[i].getState() ==
pw.printf("Main : Priority: %d\n", thread.getPriority());
pw.printf("Main : Old State: %s\n", state);
pw.printf("Main : New State: %s\n", thread.getState());
pw.printf("Main : ************************************\n"); }
Trang 37Run the program and see how the different threads work in parallel.
10
How it works
The following screenshot shows the console part of the output of the program We can seethat all the threads we have created run in parallel to do their respective jobs:
Trang 38In this screenshot, you can see how threads are created and how the ones with an evennumber are executed first, as they have the highest priority, and the others executed later,
as they have minimum priority The following screenshot shows part of the output of thelog.txt file where we write information about the status of the threads:
Every Java program has at least one execution thread When you run the program, JVMruns the execution thread that calls the main() method of the program
When we call the start() method of a Thread object, we are creating another executionthread Our program will have as many execution threads as the number of calls made tothe start() method
The Thread class has attributes to store all of the information of a thread The OS scheduleruses the priority of threads to select the one that uses the CPU at each moment and
actualizes the status of every thread according to its situation
If you don't specify a name for a thread, JVM automatically assigns it one in this format:Thread-XX, where XX is a number You can't modify the ID or status of a thread TheThread class doesn't implement the setId() and setStatus() methods as these methodsintroduce modifications in the code
Trang 39A Java program ends when all its threads finish (more specifically, when all its non-daemonthreads finish) If the initial thread (the one that executes the main() method) ends, the rest
of the threads will continue with their execution until they finish If one of the threads usesthe System.exit() instruction to end the execution of the program, all the threads willend their respective execution
Creating an object of the Thread class doesn't create a new execution thread Also, callingthe run() method of a class that implements the Runnable interface doesn't create a newexecution thread Only when you call the start() method, a new execution thread iscreated
There's more
As mentioned in the introduction of this recipe, there is another way of creating a newexecution thread You can implement a class that extends the Thread class and overridesthe run() method of this class Then, you can create an object of this class and call thestart() method to have a new execution thread
You can use the static method currentThread() of the Thread class to access the threadobject that is running the current object
You have to take into account that the setPriority() method can throw an
IllegalArgumentException exception if you try to establish priority that isn't between 1and 10
See also
The Creating threads through a factory recipe of this chapter
Trang 40Java provides an interruption mechanism that indicates to a thread that you want to finish
it One peculiarity of this mechanism is that thread objects have to check whether they havebeen interrupted or not, and they can decide whether they respond to the finalizationrequest or not A thread object can ignore it and continue with its execution
In this recipe, we will develop a program that creates a thread and forces its finalizationafter 5 seconds, using the interruption mechanism
Getting ready
The example for this recipe has been implemented using the Eclipse IDE If you use Eclipse
or a different IDE, such as NetBeans, open it and create a new Java project
How to do it
Follow these steps to implement the example:
Create a class called PrimeGenerator that extends the Thread class:
1
public class PrimeGenerator extends Thread{
Override the run() method including a loop that will run indefinitely In this2
loop, process consecutive numbers beginning from one For each number,calculate whether it's a prime number; if yes, as in this case, write it to the