
- •Contents at a Glance
- •Contents
- •About the Authors
- •About the Technical Reviewer
- •Acknowledgments
- •Introduction
- •Oracle Java Certifications: Overview
- •FAQ 1. What are the different levels of Oracle Java certification exams?
- •FAQ 4. Is OCPJP 7 prerequisite for other Oracle certification exams?
- •FAQ 5. Should I take the OCPJP 7 or OCPJP 6 exam?
- •The OCPJP 7 Exam
- •FAQ 7. How many questions are there in the OCPJP 7 exam?
- •FAQ 8. What is the duration of the OCPJP 7 exam?
- •FAQ 9. What is the cost of the OCPJP 7 exam?
- •FAQ 10. What are the passing scores for the OCPJP 7 exam?
- •FAQ 11. What kinds of questions are asked in the OCPJP 7 exam?
- •FAQ 12. What does the OCPJP 7 exam test for?
- •FAQ 13. I’ve been a Java programmer for last five years. Do I have to prepare for the OCPJP 7 exam?
- •FAQ 14. How do I prepare for the OCPJP 7 exam?
- •FAQ 15. How do I know when I’m ready to take the OCPJP 7 exam?
- •Taking the OCPJP 7 Exam
- •FAQ 16. What are my options to register for the exam?
- •FAQ 17. How do I register for the exam, schedule a day and time for taking the exam, and appear for the exam?
- •The OCPJP 7 Exam: Pretest
- •Answers with Explanations
- •Post-Pretest Evaluation
- •Essentials of OOP
- •FunPaint Application: An Example
- •Foundations of OOP
- •Abstraction
- •Encapsulation
- •Inheritance
- •Polymorphism
- •Class Fundamentals
- •Object Creation
- •Constructors
- •Access Modifiers
- •Public Access Modifier
- •Private Access Modifier
- •Protected and Default Access Modifier
- •Overloading
- •Method Overloading
- •Constructor Overloading
- •Overload resolution
- •Points to Remember
- •Inheritance
- •Runtime Polymorphism
- •An Example
- •Overriding Issues
- •Overriding: Deeper Dive
- •Invoking Superclass Methods
- •Type Conversions
- •Upcasts and Downcasts
- •Casting Between Inconvertible Types
- •Using “instanceof” for Safe Downcasts
- •Java Packages
- •Working with Packages
- •Static Import
- •Summary
- •Abstract Classes
- •Points to Remember
- •Using the “final” Keyword
- •Final Classes
- •Final Methods and Variables
- •Points to Remember
- •Using the “static” Keyword
- •Static Block
- •Points to Remember
- •Flavors of Nested Classes
- •Static Nested Classes (or Interfaces)
- •Points to Remember
- •Inner Classes
- •Points to Remember
- •Local Inner Classes
- •Points to Remember
- •Anonymous Inner Classes
- •Points to Remember
- •Enum Data Types
- •Points to Remember
- •Summary
- •Interfaces
- •Declaring and Using Interfaces
- •Points to Remember
- •Abstract Classes vs. Interfaces
- •Choosing Between an Abstract Class and an Interface
- •Object Composition
- •Composition vs. Inheritance
- •Points to Remember
- •Design Patterns
- •The Singleton Design Pattern
- •Ensuring That Your Singleton Is Indeed a Singleton
- •The Factory Design Pattern
- •Differences Between Factory and Abstract Factory Design Patterns
- •The Data Access Object (DAO) Design Pattern
- •Points to Remember
- •Summary
- •Generics
- •Using Object Type and Type Safety
- •Using the Object Class vs. Generics
- •Container Implementation Using the Object Class
- •Container Implementation Using Generics
- •Creating Generic Classes
- •Diamond Syntax
- •Interoperability of Raw Types and Generic Types
- •Generic Methods
- •Generics and Subtyping
- •Wildcard Parameters
- •Limitations of Wildcards
- •Bounded Wildcards
- •Wildcards in the Collections Class
- •Points to Remember
- •The Collections Framework
- •Why Reusable Classes?
- •Basic Components of the Collections Framework
- •Abstract Classes and Interfaces
- •Concrete Classes
- •List Classes
- •ArrayList Class
- •The ListIterator Interface
- •The LinkedList Class
- •The Set Interface
- •The HashSet Class
- •The TreeSet Class
- •The Map Interface
- •The HashMap Class
- •Overriding the hashCode() Method
- •The NavigableMap Interface
- •The Queue Interface
- •The Deque Interface
- •Comparable and Comparator Interfaces
- •Algorithms (Collections Class)
- •The Arrays Class
- •Methods in the Arrays Class
- •Array as a List
- •Points to Remember
- •Summary
- •Generics
- •Collections Framework
- •Processing Strings
- •String Searching
- •The IndexOf() Method
- •The regionMatches() Method
- •String Parsing
- •String Conversions
- •The Split() Method
- •Regular Expressions
- •Understanding regex Symbols
- •Regex Support in Java
- •Searching and Parsing with regex
- •Replacing Strings with regex
- •String Formatting
- •Format Specifiers
- •Points to Remember
- •Summary
- •Reading and Writing from Console
- •Understanding the Console Class
- •Formatted I/O with the Console Class
- •Special Character Handling in the Console Class
- •Using Streams to Read and Write Files
- •Character Streams and Byte Streams
- •Character Streams
- •Reading Text Files
- •Reading and Writing Text Files
- •“Tokenizing” Text
- •Byte Streams
- •Reading a Byte Stream
- •Data Streams
- •Writing to and Reading from Object Streams: Serialization
- •Serialization: Some More Details
- •Points to Remember
- •Summary
- •A Quick History of I/O APIs
- •Using the Path Interface
- •Getting Path Information
- •Comparing Two Paths
- •Using the Files Class
- •Checking File Properties and Metadata
- •Copying a File
- •Moving a File
- •Deleting a File
- •Walking a File Tree
- •Revisiting File Copy
- •Finding a File
- •Watching a Directory for Changes
- •Points to Remember
- •Summary
- •Introduction to JDBC
- •The Architecture of JDBC
- •Two-Tier and Three-Tier JDBC Architecture
- •Types of JDBC Drivers
- •Setting Up the Database
- •Connecting to a Database Using a JDBC Driver
- •The Connection Interface
- •Connecting to the Database
- •Statement
- •ResultSet
- •Querying the Database
- •Updating the Database
- •Getting the Database Metadata
- •Points to Remember
- •Querying and Updating the Database
- •Performing Transactions
- •Rolling Back Database Operations
- •The RowSet Interface
- •Points to Remember
- •Summary
- •Define the Layout of the JDBC API
- •Connect to a Database by Using a JDBC driver
- •Update and Query a Database
- •Customize the Transaction Behavior of JDBC and Commit Transactions
- •Use the JDBC 4.1 RowSetProvider, RowSetFactory, and RowSet Interfaces
- •Introduction to Exception Handling
- •Throwing Exceptions
- •Unhandled Exceptions
- •Try and Catch Statements
- •Programmatically Accessing the Stack Trace
- •Multiple Catch Blocks
- •Multi-Catch Blocks
- •General Catch Handlers
- •Finally Blocks
- •Points to Remember
- •Try-with-Resources
- •Closing Multiple Resources
- •Points to Remember
- •Exception Types
- •The Exception Class
- •The RuntimeException Class
- •The Error Class
- •The Throws Clause
- •Method Overriding and the Throws Clause
- •Points to Remember
- •Custom Exceptions
- •Assertions
- •Assert Statement
- •How Not to Use Asserts
- •Summary
- •Introduction
- •Locales
- •The Locale Class
- •Getting Locale Details
- •Resource Bundles
- •Using PropertyResourceBundle
- •Using ListResourceBundle
- •Loading a Resource Bundle
- •Naming Convention for Resource Bundles
- •Formatting for Local Culture
- •The NumberFormat Class
- •The Currency Class
- •The DateFormat Class
- •The SimpleDateFormat Class
- •Points to Remember
- •Summary
- •Introduction to Concurrent Programming
- •Important Threading-Related Methods
- •Creating Threads
- •Extending the Thread Class
- •Implementing the Runnable Interface
- •The Start( ) and Run( ) Methods
- •Thread Name, Priority, and Group
- •Using the Thread.sleep() Method
- •Using Thread’s Join Method
- •Asynchronous Execution
- •The States of a Thread
- •Two States in “Runnable” State
- •Concurrent Access Problems
- •Data Races
- •Thread Synchronization
- •Synchronized Blocks
- •Synchronized Methods
- •Synchronized Blocks vs. Synchronized Methods
- •Deadlocks
- •Other Threading Problems
- •Livelocks
- •Lock Starvation
- •The Wait/Notify Mechanism
- •Let’s Solve a Problem
- •More Thread States
- •timed_waiting and blocked States
- •waiting State
- •Using Thread.State enum
- •Understanding IllegalThreadStateException
- •Summary
- •Using java.util.concurrent Collections
- •Semaphore
- •CountDownLatch
- •Exchanger
- •CyclicBarrier
- •Phaser
- •Concurrent Collections
- •Apply Atomic Variables and Locks
- •Atomic Variables
- •Locks
- •Conditions
- •Multiple Conditions on a Lock
- •Use Executors and ThreadPools
- •Executor
- •Callable, Executors, ExecutorService, ThreadPool, and Future
- •ThreadFactory
- •The ThreadLocalRandom Class
- •TimeUnit Enumeration
- •Use the Parallel Fork/Join Framework
- •Useful Classes of the Fork/Join Framework
- •Using the Fork/Join Framework
- •Points to Remember
- •Summary
- •Using java.util.concurrent Collections
- •Applying Atomic Variables and Locks
- •Using Executors and ThreadPools
- •Using the Parallel Fork/Join Framework
- •Chapter 3: Java Class Design
- •Chapter 4: Advanced Class Design
- •Chapter 5: Object-Oriented Design Principles
- •Chapter 6: Generics and Collections
- •Chapter 7: String Processing
- •Chapter 8: Java I/O Fundamentals
- •Chapter 9: Java File I/O (NIO.2)
- •Chapter 10: Building Database Applications with JDBC
- •Chapter 11: Exceptions and Assertions
- •Chapter 12: Localization
- •Chapter 13: Threads
- •Chapter 14: Concurrency
- •OCPJP7 Exam (1Z0-804 a.k.a. Java SE 7 Programmer II) Topics
- •OCPJP 7 Exam (1Z0-805, a.k.a. Upgrade to Java SE 7 Programmer) Topics
- •Answers and Explanations
- •Answer Sheet
- •Answers and Explanations
- •Index

Chapter 14
Concurrency
Use java.util.concurrent collections
Apply atomic variables and locks
Exam Topics
Use Executors and ThreadPools
Use the parallel Fork/Join Framework
From the beginning, Java supported concurrency in the form of low-level threads management, locks, synchronization, and APIs for concurrency. We covered them in the preceding chapter in our discussion of the Thread class, Runnable interface, and synchronized keyword.
Since 5.0, Java also supports high-level concurrency APIs in its java.util.concurrent package. In this chapter, we’ll focus on these APIs for concurrent programming. These high-level APIs exploit today’s multi-core hardware, in which a single processor has multiple cores. These APIs are also useful for exploiting concurrency in machines that support multiple processors.
Most of the Java concurrency utilities are provided in the java.util.concurrent package. Classes to efficiently update shared variables without using locks are provided in the java.util.concurrent.atomic subpackage. The Lock interface and the classes deriving from it are provided in the java.util.concurrent.locks subpackage.
Using java.util.concurrent Collections
There are many classes in the java.util.concurrent package that provide high-level APIs for concurrent programming. In this section, we will mainly discuss synchronizer classes provided in this package. Following that, we will briefly cover the important concurrent collection classes provided in the java.util.concurrent package.
You already understand the low-level concurrency constructs (such as the use of the synchronized keyword, Runnable interface, and Thread class for creating threads) from the preceding chapter. In the case of a shared resource that needs to be accessed by multiple threads, access and modifications to the shared resource need to be protected. When you use the synchronized keyword, you employ mutexes to synchronize between threads for safe shared access. Threads also often needed to coordinate their executions to complete a bigger higher-level task. The wait/ notify pattern discussed in the last chapter is one way to coordinate the execution of multiple threads.
Using APIs for acquiring and releasing locks (using mutexes) or invoking the wait/notify methods on locks are low-level tasks. It is possible to build higher-level abstractions for thread synchronization. These high-level
abstractions for synchronizing activities of two or more threads are known as synchronizers. Synchronizers internally make use of the existing low-level APIs for thread coordination.
435
Chapter 14 ■ Concurrency
The synchronizers provided in the java.util.concurrent library and their uses are listed here:
•Semaphore controls access to one or more shared resources.
•Phaser is used to support a synchronization barrier.
•CountDownLatch allows threads to wait for a countdown to complete.
•Exchanger supports exchanging data between two threads.
•CyclicBarrier enables threads to wait at a predefined execution point. Now, we’ll discuss each of these synchronizers in turn with the help of examples.
Semaphore
A semaphore controls access to shared resources. A semaphore maintains a counter to specify the number of resources that the semaphore controls. Access to the resource is allowed if the counter is greater than zero,while a zero value of the counter indicates that no resource is available at the moment and so the access is denied.
The methods acquire() and release() are for acquiring and releasing resources from a semaphore. If a thread calls acquire() and the counter is zero (i.e., resources are unavailable), the thread waits until the counter is non-zero and then gets the resource for use. Once the thread is done using the resource, it calls release() to increment the resource availability counter.
Note if the number of resources is 1, then at a given time only one thread can access the resource; in this case, using the semaphore is similar to using a lock. Table 14-1 lists the important methods in the Semaphore class.
Table 14-1. Important Methods in the Semaphore Class
Method |
Description |
Semaphore(int permits) |
Constructor to create Semaphore objects with a given number of permits |
|
(the number of threads that can access the resource at a time). If the |
|
permit’s value is negative, the given number of release() calls must |
|
happen before acquire() calls can succeed. |
Semaphore(int permits, |
Same as the previous constructor, but this extra fair option indicates that |
boolean fair) |
the permits should be allotted on a first-come-first-served basis. |
void acquire() |
Acquires a permit if available; otherwise, it blocks until a permit becomes |
void acquire(int permits) |
available. Can throw an InterruptedException if some other thread |
|
interrupts it while waiting to acquire a permit. The overloaded version |
|
takes a number of permits as an argument. |
void |
Same as the acquire() method, but this thread cannot be interrupted |
acquireUninterruptibly() |
while waiting to acquire a permit. |
boolean tryAcquire() |
Acquires a permit from the semaphore if available at the time of the call |
boolean tryAcquire(long timeout, |
and returns true; if unavailable, it returns false immediately (without |
TimeUnit unit) |
blocking). The overloaded tryAcquire() method additionally takes a |
|
time-out argument—the thread blocks to acquire a permit from the |
|
semaphore until a given time-out period. |
void release() |
Releases a permit from the semaphore. The overloaded version specifies |
void release(int permits) |
the number of permits to release. |
|
|
436
Chapter 14 ■ Concurrency
Let’s assume that there are two ATM machines available in a ATM machine room. Therefore, only two people are allowed at a time in the room. There are five people waiting outside to use the ATM machines. The situation can be simulated by the code in Listing 14-1, in which each ATM machine is treated as a resource controlled by semaphore.
Listing 14-1. ATMRoom.java
import java.util.concurrent.Semaphore;
//This class simulates a situation where an ATM room has only two ATM machines
//and five people are waiting to access the machine. Since only one person can access
//an ATM machine at a given time, others wait for their turn
class ATMRoom {
public static void main(String []args) {
// assume that only two ATM machines are available in the ATM room Semaphore machines = new Semaphore(2);
// list of people waiting to access the machine new Person(machines, "Mickey");
new Person(machines, "Donald"); new Person(machines, "Tom"); new Person(machines, "Jerry"); new Person(machines, "Casper");
}
}
//Each Person is an independent thread; but their access to the common resource
//(two ATM machines in the ATM machine room in this case) needs to be synchronized. class Person extends Thread {
private Semaphore machines;
public Person(Semaphore machines, String name) { this.machines = machines; this.setName(name);
this.start();
}
public void run() { try {
System.out.println(getName() + " waiting to access an ATM machine"); machines.acquire();
System.out.println(getName() + " is accessing an ATM machine"); Thread.sleep(1000); // simulate the time required for withdrawing amount System.out.println(getName() + " is done using the ATM machine"); machines.release();
} catch(InterruptedException ie) { System.err.println(ie);
}
}
}
Here is the output of the program in one sample run:
Mickey waiting to access an ATM machine Tom waiting to access an ATM machine
437
Chapter 14 ■ Concurrency
Jerry waiting to access an ATM machine Donald waiting to access an ATM machine Casper waiting to access an ATM machine Tom is accessing an ATM machine
Mickey is accessing an ATM machine Tom is done using the ATM machine Mickey is done using the ATM machine Jerry is accessing an ATM machine Donald is accessing an ATM machine Donald is done using the ATM machine Jerry is done using the ATM machine Casper is accessing an ATM machine Casper is done using the ATM machine
Now let’s analyze how this program works. People waiting to access an ATM machine are simulated by creating a Person class that extends Thread. The run() method in the Thread class acquires a semaphore, simulates withdrawing money from the ATM machine, and releases the semaphore.
The main() method simulates an ATM room with two ATM machines by creating a Semaphore object with two permits. People waiting in the queue to access the ATM machine are implemented by just adding them to the
Semaphore object.
As you can see from the program output, the semaphore allows only two threads at a time and the other threads keep waiting. When a thread releases the semaphore, another thread acquires it. Cool, isn’t it?
CountDownLatch
This synchronizer allows one or more threads to wait for a countdown to complete. This countdown could be for a set of events to happen or until a set of operations being performed in other threads completes. Table 14-2 lists important methods in this class.
Table 14-2. Important Methods in the CountDownLatch Class
|
|
Method |
Description |
CountDownLatch(int count) |
Creates an instance of CountDownLatch with the number of times the |
|
countDown() method must be called before the threads waiting with await() |
|
can continue execution. |
void await() |
If the current count in CountDownLatch object is zero, it immediately returns; |
|
otherwise, the thread blocks until the countdown reaches zero. Can throw an |
|
InterruptedException. |
boolean await(long timeout, |
Same as the previous method, await(), but takes an additional time-out |
TimeUnit unit) |
argument. If the thread returns successfully after the count reaches zero, this |
|
method returns true; if the thread returns because of time-out, it returns false. |
void countDown() |
Reduces the number of counts by one in this CountDownLatch object. If the |
|
count reaches zero, all the (a)waiting threads are released. If the current count |
|
is already zero, nothing happens. |
long getCount() |
Returns the pending counts in this CountDownLatch object. |
|
|
438
Chapter 14 ■ Concurrency
When you create a CountDownLatch, you initialize it with an integer, which represents a count value. Threads would wait (by calling the await() method) for this count to reach zero. Once zero is reached, all threads are released; any other calls to await() would return immediately since the count is already zero. The counter value can be decremented by one by calling the countDown() method. You can get the current value of the counter using the getCount() method. See Listing 14-2.
Listing 14-2. RunningRaceStarter.java
import java.util.concurrent.*;
//this class simulates the start of a running race by counting down from 5. It holds
//three runner threads to be ready to start in the start line of the race and once the count down
//reaches zero, all the three runners start running...
class RunningRaceStarter {
public static void main(String []args) throws InterruptedException { CountDownLatch counter = new CountDownLatch(5);
// count from 5 to 0 and then start the race
// instantiate three runner threads new Runner(counter, "Carl");
new Runner(counter, "Joe"); new Runner(counter, "Jack");
System.out.println("Starting the countdown "); long countVal = counter.getCount(); while(countVal > 0) {
Thread.sleep(1000); // 1000 milliseconds = 1 second System.out.println(countVal);
if(countVal == 1) {
//once counter.countDown(); in the next statement is called,
//Count down will reach zero; so shout "Start" System.out.println("Start");
}
counter.countDown(); // count down by 1 for each second countVal = counter.getCount();
}
}
}
//this Runner class simulates a track runner in a 100-meter dash race. The runner waits until the
//count down timer gets to zero and then starts running
class Runner extends Thread { private CountDownLatch timer;
public Runner(CountDownLatch cdl, String name) { timer = cdl;
this.setName(name);
System.out.println(this.getName() + " ready and waiting for the count down to start"); start();
}
439