Java 9 Concurrency Cookbook - Second Edition
eBook - ePub

Java 9 Concurrency Cookbook - Second Edition

Javier Fernandez Gonzalez

Share book
  1. 594 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Java 9 Concurrency Cookbook - Second Edition

Javier Fernandez Gonzalez

Book details
Book preview
Table of contents
Citations

About This Book

Master the art of fast, effective Java development with the power of concurrent and parallel programmingAbout This Book• Get detailed coverage of important recipes on multi-threading and parallel programming• This book takes a close look at the Java 9 APIs and their impact on concurrency• See practical examples on thread safety, high-performance classes, safe sharing, and a whole lot moreWho This Book Is ForThe book is for Java developers and programmers at an intermediate to advanced level. It will be especially useful for developers who want to take advantage of task-based recipes using Java 9's concurrent API to program thread-safe solutions.What You Will Learn• Find out to manage the basic components of the Java Concurrency API• Use synchronization mechanisms to avoid data race conditions and other problems of concurrent applications• Separate the thread management from the rest of the application with the Executor framework• Solve problems using a parallelized version of the divide and conquer paradigm with the Fork / Join framework• Process massive data sets in an optimized way using streams and reactive streams• See which data structures we can use in concurrent applications and how to use them• Practice efficient techniques to test concurrent applications• Get to know tips and tricks to design concurrent applicationsIn DetailWriting concurrent and parallel programming applications is an integral skill for any Java programmer. Java 9 comes with a host of fantastic features, including significant performance improvements and new APIs.This book will take you through all the new APIs, showing you how to build parallel and multi-threaded applications. The book covers all the elements of the Java Concurrency API, with essential recipes that will help you take advantage of the exciting new capabilities.You will learn how to use parallel and reactive streams to process massive data sets. Next, you will move on to create streams and use all their intermediate and terminal operations to process big collections of data in a parallel and functional way.Further, you'll discover a whole range of recipes for almost everything, such as thread management, synchronization, executors, parallel and reactive streams, and many more. At the end of the book, you will learn how to obtain information about the status of some of the most useful components of the Java Concurrency API and how to test concurrent applications using different tools.Style and approachThis recipe-based book will allow you to explore the exciting capabilities of concurrency in Java. After reading this book, you will be able to comfortably build parallel applications in Java 9.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Java 9 Concurrency Cookbook - Second Edition an online PDF/ePUB?
Yes, you can access Java 9 Concurrency Cookbook - Second Edition by Javier Fernandez Gonzalez in PDF and/or ePUB format, as well as other popular books in Ciencia de la computación & Programación en Java. We have over one million books available in our catalogue for you to explore.

Information

Year
2017
ISBN
9781787125438

Customizing Concurrency Classes

In this chapter, we will cover the following topics:
  • Customizing the ThreadPoolExecutor class
  • Implementing a priority-based Executor class
  • Implementing the ThreadFactory interface to generate custom threads
  • Using our ThreadFactory in an Executor object
  • Customizing tasks running in a scheduled thread pool
  • Implementing the ThreadFactory interface to generate custom threads for the fork/join framework
  • Customizing tasks running in the fork/join framework
  • Implementing a custom Lock class
  • Implementing a transfer queue-based on priorities
  • Implementing your own atomic object
  • Implementing your own stream generator
  • Implementing your own asynchronous stream

Introduction

The Java Concurrency API provides a lot of interfaces and classes to implement concurrent applications. They provide low-level mechanisms, such as the Thread class, the Runnable or Callable interfaces, or the synchronized keyword. They also provide high-level mechanisms, such as the Executor framework and the fork/join framework added in the Java 7 release, or the Stream framework added in Java 8, to process big sets of data. Despite this, you may find yourself developing a program where the default configuration and/or implementation of the Java API doesn't meet your needs.
In this case, you may need to implement your own custom concurrent utilities, based on the ones provided by Java. Basically, you can:
  • Implement an interface to provide the functionality defined by that interface, for example, the ThreadFactory interface.
  • Override some methods of a class to adapt its behavior to your needs. For example, overriding the onAdvance() method of the Phaser class that, by default, does nothing useful and is supposed to be overridden to offer some functionality.
Through the recipes of this chapter, you will learn how to change the behavior of some Java concurrency API classes without the need to design a concurrency framework from scratch. You can use these recipes as an initial point to implement your own customizations.

Customizing the ThreadPoolExecutor class

The Executor framework is a mechanism that allows you to separate thread creation from its execution. It's based on the Executor and ExecutorService interfaces with the ThreadPoolExecutor class that implements both the interfaces. It has an internal pool of threads and provides methods that allow you to send two kinds of tasks and execute them in the pooled threads. These tasks are:
  • The Runnable interface to implement tasks that don't return a result
  • The Callable interface to implement tasks that return a result
In both cases, you only send the task to the executor. The executor uses one of its pooled threads or creates a new one to execute those tasks. It also decides the moment in which the task is executed.
In this recipe, you will learn how to override some methods of the ThreadPoolExecutor class to calculate the execution time of the tasks that you will execute in the executor and write about the executor in console statistics when it completes its execution.

Getting ready

The example of 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:
  1. Create a class named MyExecutor that extends the ThreadPoolExecutor class:
 public class MyExecutor extends ThreadPoolExecutor { 
  1. Declare a private ConcurrentHashMap attribute parameterized by the String and Date classes, named startTimes:
 private final ConcurrentHashMap<Runnable, Date> startTimes; 
  1. Implement the constructor for the class. Call a constructor of the parent class using the super keyword and initialize the startTime attribute:
 public MyExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
workQueue);
startTimes=new ConcurrentHashMap<>();
}
  1. Override the shutdown() method. Write in the console information about the executed, running, and pending tasks. Then, call the shutdown() method of the parent class using the super keyword:
 @Override 
public void shutdown() {
System.out.printf("MyExecutor: Going to shutdown.\n");
System.out.printf("MyExecutor: Executed tasks: %d\n",
getCompletedTaskCount());
 System.out.printf("MyExecutor: Running tasks: %d\n",
getActiveCount()); System.out.printf("MyExecutor: Pending tasks: %d\n",
getQueue().size());
super.shutdown();
}
  1. Override the shutdownNow() method. Write in the console information about the executed, running, and pending tasks. Then, call the shutdownNow() method of the parent class using the super keyword:
 @Override 
public List<Runnable> shutdownNow() {
System.out.printf("MyExecutor: Going to immediately
shutdown.\n");
System.out.printf("MyExecutor: Executed tasks: %d\n",
getCompletedTaskCount());
System.out.printf("MyExecutor: Running tasks: %d\n",
getActiveCount());
System.out.printf("MyExecutor: Pending tasks: %d\n",
getQueue().size());
return super.shutdownNow();
}
  1. Override the beforeExecute() method. Write a message in the console with the name of the thread that is going to execute the task and the hash code of the task. Store the start date in HashMap using the hash code of the task as the key:
 @Override 
protected void beforeExecute(Thread t, Runnable r) {
System.out.printf("MyExecutor: A task is beginning: %s : %s\n",
t.getName(),r.hashCode());
startTimes.put(r, new Date());
}
  1. Override the afterExecute() method. Write a message in the console with the result of the task and calculate the running time of the task after subtracting the start date of the task stored in HashMap of the current date:
 @Override 
protected void afterExecute(Runnable r, Throwable t) {
Future<?> result=(Future<?>)r;
try {
System.out.printf("*********************************\n");
System.out.printf("MyExecutor: A task is finishing.\n");
 System.out.printf("MyExecutor: Result: %s\n",
result.get());
Date startDate=startTimes.remove(r);
Date finishDate=new Date();
long diff=finishDate.getTime()-startDate.getTime();
System.out.printf("MyExecutor: Duration: %d\n",diff);
System.out.printf("*********************************\n");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
  1. Create a class named SleepTwoSecondsTask that implements the Callable interface parameterized by the String class. Implement the call() method. Put the current thread to sleep for 2 seconds and return the current date converted into a String type:
 public class SleepTwoSecondsTask implements Callable<String> { 

public String call() throws Exception {
TimeUnit.SECONDS.sleep(2);
return new Date().toString();
}

}
  1. Implement the main...

Table of contents