Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Java 9 Concurrency Cookbook, Second Edition
Java 9 Concurrency Cookbook, Second Edition

Java 9 Concurrency Cookbook, Second Edition: Build highly scalable, robust, and concurrent applications , Second Edition

Arrow left icon
Profile Icon Javier Fernández González
Arrow right icon
€32.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (1 Ratings)
eBook Apr 2017 594 pages 2nd Edition
eBook
€32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Javier Fernández González
Arrow right icon
€32.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (1 Ratings)
eBook Apr 2017 594 pages 2nd Edition
eBook
€32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Java 9 Concurrency Cookbook, Second Edition

Basic Thread Synchronization

In this chapter, we will cover the following topics:

  • Synchronizing a method
  • Using conditions in synchronized code
  • Synchronizing a block of code with a lock
  • Synchronizing data access with read/write locks
  • Using multiple conditions in a lock
  • Advanced locking with the StampedLock class

Introduction

One of the most common situations in concurrent programming occurs when more than one execution thread shares a resource. In a concurrent application, it is normal for multiple threads to read or write the same data structure or have access to the same file or database connection. These shared resources can provoke error situations or data inconsistency, and we have to implement mechanisms to avoid these errors. These situations are called race conditions and they occur when different threads have access to the same shared resource at the same time. Therefore, the final result depends on the order of the execution of threads, and most of the time, it is incorrect. You can also have problems with change visibility. So if a thread changes the value of a shared variable, the changes would only be written in the local cache of that thread; other threads will not have access to the change (they will only...

Synchronizing a method

In this recipe, you will learn how to use one of the most basic methods of synchronization in Java, that is, the use of the synchronized keyword to control concurrent access to a method or a block of code. All the synchronized sentences (used on methods or blocks of code) use an object reference. Only one thread can execute a method or block of code protected by the same object reference.

When you use the synchronized keyword with a method, the object reference is implicit. When you use the synchronized keyword in one or more methods of an object, only one execution thread will have access to all these methods. If another thread tries to access any method declared with the synchronized keyword of the same object, it will be suspended until the first thread finishes the execution of the method. In other words, every method declared with the synchronized keyword is a critical section, and Java...

Using conditions in synchronized code

A classic problem in concurrent programming is the producer-consumer problem. We have a data buffer, one or more producers of data that save it in the buffer, and one or more consumers of data that take it from the buffer.

As the buffer is a shared data structure, we have to control access to it using a synchronization mechanism, such as the synchronized keyword, but here we have more limitations. A producer can't save data in the buffer if it's full, and a consumer can't take data from the buffer if it's empty.

For these types of situations, Java provides the wait(), notify(), and notifyAll() methods implemented in the Object class. A thread can call the wait() method inside a synchronized block of code. If it calls the wait() method outside a synchronized block of code, JVM throws an IllegalMonitorStateException exception. When the thread calls the wait...

Synchronizing a block of code with a lock

Java provides another mechanism for synchronizing blocks of code. It's a more powerful and flexible mechanism than the synchronized keyword. It's based on the Lock (of the java.util.concurrent.locks package) interface and classes that implement it (as ReentrantLock). This mechanism presents some advantages, which are as follows:

  • It allows you to structure synchronized blocks in a more flexible way. With the synchronized keyword, you only have control over a synchronized block of code in a structured way. However, the Lock interface allows you to get more complex structures to implement your critical section.
  • The Lock interface provides additional functionalities over the synchronized keyword. One of the new functionalities is implemented by the tryLock() method. This method tries to get control of the lock, and if it can't, because it's used by another...

Synchronizing data access with read/write locks

One of the most significant improvements offered by locks is the ReadWriteLock interface and the ReentrantReadWriteLock class, the unique class that implements that interface. This class has two locks: one for read operations and one for write operations. There can be more than one thread using read operations simultaneously, but only one thread can use write operations. If a thread is doing a write operation, other threads can't write or read.

In this recipe, you will learn how to use a ReadWriteLock interface by implementing a program that uses it to control access to an object that stores the prices of two products.

Getting ready...

You should read the Synchronizing a block of code with a lock recipe to better...

Using multiple conditions in a lock

A lock may be associated with one or more conditions. These conditions are declared in the Condition interface. The purpose of these conditions is to allow threads to have control of a lock and check whether a condition is true or not. If it's false, the thread will be suspended until another thread wakes it up. The Condition interface provides the mechanisms to suspend a thread and wake up a suspended thread.

A classic problem in concurrent programming is the producer-consumer problem. We have a data buffer, one or more producers of data that save it in the buffer, and one or more consumers of data that take it from the buffer, as explained earlier in this chapter.

In this recipe, you will learn how to implement the producer-consumer problem using locks and conditions.

...

Advanced locking with the StampedLock class

The StampedLock class provides a special kind of lock that is different from the ones provided by the Lock or ReadWriteLock interfaces. In fact, this class doesn't implement these interfaces, but the functionality it provides is very similar.

The first point to note about this kind of lock is that its main purpose is to be a helper class to implement thread-safe components, so its use will not be very common in normal applications.

The most important features of StampedLock locks are as follows:

  • You can obtain control of the lock in three different modes:
    • Write: In this mode, you get exclusive access to the lock. No other thread can have control of the lock in this mode.
    • Read: In this mode, you have non-exclusive access to the lock. There can be other threads that have access to the lock in this mode or the Optimistic Read mode.
    • Optimistic Read: Here, the thread...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

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

Description

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

Who is this book for?

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

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 25, 2017
Length: 594 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787125438
Vendor :
Oracle
Category :
Languages :
Concepts :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Apr 25, 2017
Length: 594 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787125438
Vendor :
Oracle
Category :
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
Mastering Concurrency Programming with Java 9, Second Edition
€41.99
Java 9 Concurrency Cookbook, Second Edition
€41.99
Java 9 Programming By Example
€36.99
Total 120.97 Stars icon

Table of Contents

11 Chapters
Thread Management Chevron down icon Chevron up icon
Basic Thread Synchronization Chevron down icon Chevron up icon
Thread Synchronization Utilities Chevron down icon Chevron up icon
Thread Executors Chevron down icon Chevron up icon
Fork/Join Framework Chevron down icon Chevron up icon
Parallel and Reactive Streams Chevron down icon Chevron up icon
Concurrent Collections Chevron down icon Chevron up icon
Customizing Concurrency Classes Chevron down icon Chevron up icon
Testing Concurrent Applications Chevron down icon Chevron up icon
Additional Information Chevron down icon Chevron up icon
Concurrent Programming Design Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(1 Ratings)
5 star 0%
4 star 100%
3 star 0%
2 star 0%
1 star 0%
Nirmal Tiwari Jun 02, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Just reading. The concept of concurrency in terms of lambda expressions is well explained in this book. The quality of papers and printing is excellent.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.