Java 7 Concurrency Cookbook


Java 7 Concurrency Cookbook
eBook: $29.99
Formats: PDF, PacktLib, ePub and Mobi formats
$25.49
save 15%!
Print + free eBook + free PacktLib access to the book: $79.98    Print cover: $49.99
$49.99
save 37%!
Free Shipping!
UK, US, Europe and selected countries in Asia.
Also available on:
Overview
Table of Contents
Author
Support
Sample Chapters

Master all that Java 7 has to offer for concurrent programming Get to grips with thread management, the Fork/Join framework, concurrency classes and much more in this book and e-book A practical Cookbook packed with recipes for achieving the most important Java Concurrency tasks

Book Details

Language : English
Paperback : 364 pages [ 235mm x 191mm ]
Release Date : October 2012
ISBN : 1849687889
ISBN 13 : 9781849687881
Author(s) : Javier Fernández González
Topics and Technologies : All Books, Application Development, Oracle Other, Cookbooks, Enterprise, Java, Oracle

Table of Contents

Preface
Chapter 1: Thread Management
Chapter 2: Basic Thread Synchronization
Chapter 3: Thread Synchronization Utilities
Chapter 4: Thread Executors
Chapter 5: Fork/Join Framework
Chapter 6: Concurrent Collections
Chapter 7: Customizing Concurrency Classes
Chapter 8: Testing Concurrent Applications
Free Download Chapter
Index
  • Chapter 1: Thread Management
    • Introduction
    • Creating and running a thread
    • Getting and setting thread information
    • 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 local thread variables
    • Grouping threads into a group
    • Processing uncontrolled exceptions in a group of threads
    • Creating threads through a factory
    • Chapter 2: Basic Thread Synchronization
      • Introduction
      • Synchronizing a method
      • Arranging independent attributes in synchronized classes
      • Using conditions in synchronized code
      • Synchronizing a block of code with a Lock
      • Synchronizing data access with read/write locks
      • Modifying Lock fairness
      • Using multiple conditions in a Lock
      • Chapter 3: Thread Synchronization Utilities
        • Introduction
        • Controlling concurrent access to a resource
        • Controlling concurrent access to multiple copies of a resource
        • Waiting for multiple concurrent events
        • Synchronizing tasks in a common point
        • Running concurrent phased tasks
        • Controlling phase change in concurrent phased tasks
        • Changing data between concurrent tasks
        • Chapter 4: Thread Executors
          • Introduction
          • Creating a thread executor
          • Creating a fixed-size thread executor
          • Executing tasks in an executor that returns a result
          • Running multiple tasks and processing the first result
          • Running multiple tasks and processing all the results
          • Running a task in an executor after a delay
          • Running a task in an executor periodically
          • Canceling a task in an executor
          • Controlling a task finishing in an executor
          • Separating the launching of tasks and the processing of their results in an executor
          • Controlling rejected tasks of an executor
          • Chapter 5: Fork/Join Framework
            • Introduction
            • Creating a Fork/Join pool
            • Joining the results of the tasks
            • Running tasks asynchronously
            • Throwing exceptions in the tasks
            • Canceling a task
            • Chapter 6: Concurrent Collections
              • Introduction
              • Using non-blocking thread-safe lists
              • Using blocking thread-safe lists
              • Using blocking thread-safe lists ordered by priority
              • Using thread-safe lists with delayed elements
              • Using thread-safe navigable maps
              • Generating concurrent random numbers
              • Using atomic variables
              • Using atomic arrays
              • Chapter 7: Customizing Concurrency Classes
                • Introduction
                • 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
                • Chapter 8: Testing Concurrent Applications
                  • Introduction
                  • Monitoring a Lock interface
                  • Monitoring a Phaser class
                  • Monitoring an Executor framework
                  • Monitoring a Fork/Join pool
                  • Writing effective log messages
                  • Analyzing concurrent code with FindBugs
                  • Configuring Eclipse for debugging concurrency code
                  • Configuring NetBeans for debugging concurrency code
                  • Testing concurrency code with MultithreadedTC
                  • Free Download Chapter
                    • You can download the Free Download Chapter from
                    • http://www.packtpub.com/sites/default/files/downloads/Building a
                    • Team and Working from Different Localities.pdf

                    Javier Fernández González

                    Javier Fernández González is a software architect with over 10 years experience with Java technologies. He has worked as a teacher, researcher, programmer, analyst, and now as an architect in all types of projects related to Java, especially J2EE. As a teacher, he has taught over 1,000 hours of training in basic Java, J2EE, and Struts framework. As a researcher, he has worked in the field of information retrieval, developing applications for processing large amount of data in Java and has participated as a co-author on several journal articles and conference presentations. In recent years, he has worked on developing J2EE web applications for various clients from different sectors (public administration, insurance, healthcare, transportation, and so on). He currently works as a software architect at Capgemini developing and maintaining applications for an insurance company.
                    Sorry, we don't have any reviews for this title yet.

                    Code Downloads

                    Download the code and support files for this book.


                    Submit Errata

                    Please let us know if you have found any errors not listed on this list by completing our errata submission form. Our editors will check them and add them to this list. Thank you.


                    Errata

                    - 23 submitted: last submission 07 Aug 2013

                    On page 2 of this book (that is, Preface), the link given for Chapter 9, http://www.packtpub.com/sites/default/files/downloads/Additional, should be http://www.packtpub.com/sites/default/files/downloads/Additional%20%20Information.pdf

                    On page 2 of this book (that is, Preface), the link given for Appendix, http://http://www.packtpub.com/sites/default/files/downloads/Concurrent, should be http://www.packtpub.com/sites/default/files/downloads/Concurrent%20%20Programming%20Design.pdf

                    Please don't refer to the link given in the TOC to download the free chapters. Instead, to download Chapter 9, go to: http://www.packtpub.com/sites/default/files/downloads/Additional%20%20Information.pdf and to download Appendix, go to: http://www.packtpub.com/sites/default/files/downloads/Concurrent%20%20Programming%20Design.pdf

                    On page 27, in the How it works... section, it is given that "After the first 10 seconds, we have 30 threads in the queue", which appears to be incorrect. The correct sentence is, "After the first 10 seconds, we have 30 events in the queue". Replace 30 threads with 30 events.

                    On page 39, in the fourth item, before the if statement, replace "System.out.printf("%s : %f\n",Thread.currentThread(). getId(),result);" with "System.out.printf("%s : %d\n",Thread.currentThread().getId(),result);". Here, %f is replaced with %d.

                    On page 157 and 160, replace "System.out.printf("Main: Canceled: %s\n",result.isCanceled());" with "System.out.printf("Main: Cancelled: %s\n",result.isCancelled());"

                    On page 181, point 1, replace "Create a class named Document. It will generate a string matrix that will simulate a document. public class Document {" with "Create a class named DocumentMock. It will generate a string matrix that will simulate a document. public class DocumentMock {"

                    On page 183, replace "protected Integer compute() { int result;" with "protected Integer compute() { int result=null;"

                    On page 201, "Point 19:for (int i=start; i<end; i++){if (array[i]==number) {replace withfor (int i=start; i<end; i++){if (numbers[i]==number) {Point 22:Task task1=new Task(array,start,mid,number,manager);Task task2=new Task(array,mid,end,number,manager);replace withTask task1=new Task(numbers,start,mid,number,manager);Task task2=new Task(numbers,mid,end,number,manager); "

                    On page 202, replace "public Task(int numbers[], int start, int end, int number,TaskManager manager){" with "public SearchNumberTask(int numbers[], int start, int end, int number, TaskManager manager){"

                    On page 204, replace "System.out.printf("Task: Canceled task from %d to%d",start,end);" with "System.out.printf("Task: Canceled task from %d to %d\n",start,end);" And in point 31, replace "Task task=new Task(array,0,1000,5,manager);" with "SearchNumberTask task=new SearchNumberTask(array,0,1000,5,manager);

                    In Chapter 6, <i>Using thread-safe lists with delayed elements</i>, sometimes the name DelayedQueue is used when the correct name is DelayQueue.

                    On page 247, replace point 11 with:"Create a list of Future objects parameterized with the String class to store theresultant objects of the tasks you're going to send to the executor.List<Future<String>> results=new ArrayList<>();"

                    On page 277, replace point 1. with "Create a class named MyAbstractQueuedSynchronizer that extends the AbstractQueuedSynchronizer class.public class MyAbstractQueuedSynchronizer extendsAbstractQueuedSynchronizer {."

                    On page 269, in point 11 and point 19, Task class have to be replaced by MyRecursiveTask.  

                    n page 302, replace point 16 with:"Display the number and the name of the threads queued for the lock.System.out.printf("Lock: Queued Threads: %s\n",lock.hasQueuedThreads());if (lock.hasQueuedThreads()){"</p><p>On page 310, replace bullet 13 with:"Implement the showLog() method that receives Executor as parameter.Write information about the size of the pool, the number of tasks, and the statusof the executor.private static void showLog(ThreadPoolExecutor executor) {System.out.printf("*********************\n");System.out.printf("Main: Executor Log\n");"

                    On page 317, replace "sb.append(record.getMessage()+"\n");" with "sb.append(record.getMessage()+"\n");"

                    On page 57, in the declaration of the storage object, replace "private List<Date> storage;" with "private LinkedList<Date> storage;".

                    On page 155, replace the name of the method schedulledWithFixedRate() with schedulledWithFixedDelay().

                    On page 31, numbered bullet 3, replace "This method will create an object of the UnsafeTask class and start three threads using that object, sleeping for 2 seconds between each thread." with "This method will create an object of the UnSafeTask class and start ten threads using that object"

                    On page 58, numbered bullet 3, replace "storage.offer(new Date())" with "storage.add(new Date())".

                    On page 183, replace "protected Integer compute() { int result;" with "protected Integer compute() { int result=null;" Should be : Integer result = null


                    On page 20,

                    Point 6.
                    try {
                    TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                    e.printStackTrace();
                    };

                    should be
                    try {
                    TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                    e.printStackTrace();
                    return; // Add return; to break run() method;
                    };


                    On page 32, Implement the run() method. "It has the same functionality as the run() method of UnsafeClass" should be  "It has the same functionality as the run() method of UnsafeTask"

                    On page 49,

                    Point 15. Write the initial balance to the console.
                    System.out.printf("Account : Initial Balance: %f\n",account.
                    getBalance());
                    Start the threads.
                    companyThread.start();
                    bankThread.start();

                    should be

                    15. Write the initial balance to the console then start these threads.
                    System.out.printf("Account : Initial Balance: %f\n",account.getBalance());
                    companyThread.start();
                    bankThread.start();

                    On page 50,

                    Now, add the synchronize keyword as you learned before and run the program  
                    again.
                    should be
                    Now, add the synchronized keyword as you learned before and run the program  
                    again

                    On page 88,

                    This parameter must take a Boolean value.
                    Should be :
                    This parameter must take a boolean value.

                    On page 114,

                    It receives two parameters: the number of the current phase and the number of  
                    registered participants; it returns a Boolean value
                    Should be :
                    It receives two parameters: the number of the current phase and the number of  
                    registered participants; it returns a boolean value

                    On page 123,

                    15. Now, implement the main class of the example by creating a class named  
                    Core and add the main() method to it.
                    public class Core {
                    Should be :
                    15. Now, implement the main class of the example by creating a class named  
                    Main and add the main() method to it.
                    public class Main {

                    On page 101,

                    22. Process all the rows assigned to this thread. For each row, count the  
                    number of occurrences of the number you are searching for and store this  
                    number in the corresponding position of the Results object.
                    Should be :
                    22. Process all the rows assigned to this thread. For each row, count the  
                    number of occurrences of the number you are searching for and store this  
                    number in the corresponding position of the results object.


                    On page 119,

                    In the Core class, when you created the MyPhaser object
                    Should be :
                    In the Main class, when you created the MyPhaser object

                    On page 225,

                    You called the poll() method and if it returns an Event class, you increment  
                    a counter.
                    Should be :
                    You called the poll() method and if it returns an Event object, you increment  
                    a counter.

                     

                    Errata type: Code| Page number: 225 | Errata date: 28 June 2013

                    You called the poll() method and if it returns an Event class, you increment..

                    Should be:

                    You called the poll() method and if it returns an Event object, you increment a counter.

                     

                     

                    Errata type: Typo| Page number: 254 | Errata date: 28 June 2013

                    It receives the name and the Runnable object to execute as parameters.

                    Should be:

                    It receives the name target and the Runnable object to execute as parameters.

                     

                     

                    Errata type: Typo| Page number: 271 | Errata date: 28 June 2013

                    This factory has to implement the ForkJoinPool.ForkJoinWorkerThreadFactory class.

                    Should be:

                    This factory has to implement the ForkJoinPool.ForkJoinWorkerThreadFactory interface.

                     

                     

                    Errata type: Code| Page number: 252 | Errata date: 28 June 2013

                    This class has a Priority attribute that is used to store the priority of the tasks.

                    Should be:

                    This class has a priority attribute that is used to store the priority of the tasks.

                     

                     

                    Errata type: Typo| Page number: 267 | Errata date: 28 June 2013

                    As we mentioned earlier, the constructor of the MyScheduledClass class receives the original...

                    Should be:

                    As we mentioned earlier, the constructor of the MyScheduledTask class receives the original...

                     

                     

                    Errata type: Typo| Page number: 276 | Errata date: 28 June 2013

                    19. Send the task to the pool using the execute() method. pool.invoke(task);

                    Should be:

                    19. Send the task to the pool using the execute() method. pool.execute(task);

                     

                     

                    Errata type: Typo| Page number: 288 | Errata date: 28 June 2013

                    29. Implement the run() method. It consumes 1002 Events (all the events generated in the example) using the take() method and write the number of the thread that generated the event and its priority in the console.

                    Should be:

                    29. Implement the run() method. It consumes 1002 Events (all the events generated in the example) using the take() method and write the name of the thread that generated the event and its priority in the console.

                     

                     

                     

                    Errata type: Typo| Page number: 132 | Errata date: 28 June 2013

                    If you send more tasks than the number of threads, the remaining tasks will be blocked until there is a free thread to process them This method receives the maximum number of threads as a parameter you want to have in your executor.

                    Should be:

                    If you send more tasks than the number of threads, the remaining tasks will be blocked until there is a free thread to process them. This method receives the maximum number of threads as a parameter you want to have in your executor.

                    Missing . between them and This.

                     

                     

                    Errata type: Typo| Page number: 143 | Errata date: 28 June 2013

                    18. Call the invokeAll() method of the ThreadPoolExecutor class. This class will return the list of the Future objects created earlier.

                    Should be:

                    18. Call the invokeAll() method of the ThreadPoolExecutor class. This method will return the list of the Future objects created earlier.

                     

                     

                    Errata type: Typo| Page number: 166 | Errata date: 28 June 2013

                    18. Once the CompletionService object is created, you create two ReportRequest objects that execute three ReportGenerator tasks, each one in CompletionService, and a ReportSender task that will process the results generated by the asks sent by the two ReportRequest objects.

                    Should be:

                    Once the CompletionService object is created, you create two ReportRequest objects that execute two ReportGenerator tasks, each one in CompletionService, and a ReportProcessor task that will process the results generated by the asks sent by the two ReportRequest objects.

                     

                     

                    Errata type: Typo| Page number: 291 | Errata date: 28 June 2013

                    All the methods are declared in the TransferQueue interface and the take() method implemented in the PriorityBlockingQueue interface.

                    Should be:

                    All the methods are declared in the TransferQueue interface and the take() method implemented in the PriorityBlockingQueue class.

                     

                     

                     

                    Errata type: Typo| Page number: 130 | Errata date: 28 June 2013

                    When the last task arrives to the server, the executor has a pool of 100 tasks and 97 active threads.

                    Should be:

                    When the last task arrives to the server, the executor has a pool of 100 tasks and 90 active threads.

                     

                     

                    Errata type: Typo| Page number: 133 | Errata date: 28 June 2013

                    We used the getTaskCount() method to show how many you have sent to the executor.

                    Should be:

                    We used the getTaskCount() method to show how many tasks you have sent to the executor.

                     

                     

                     

                    Errata type: Typo| Page number: 141 | Errata date: 28 June 2013

                    17. Create two String objects named user and password and initialize them with the test value.

                    Should be:

                    17. Create two String objects named username and password and initialize them with the test value.

                    Errata type: Typo| Page number: 147 | Errata date: 28 June 2013

                    The ExecutorService class provides another version of the invokeAll() method:

                    Should be:

                    The ExecutorService interface provides another version of the invokeAll() method:

                     

                     

                    Errata type: Typo| Page number: 161 | Errata date: 28 June 2013

                    Normally, when you execute concurrent tasks using an executor, you will send Runnable or Callable tasks to the executor and get Future objects to control the method.

                    Should be:

                    Normally, when you execute concurrent tasks using an executor, you will send Runnable or Callable tasks to the executor and get Future objects to control the task.

                     

                     

                    Errata type: Typo| Page number: 162 | Errata date: 28 June 2013

                    Long duration=(long)(Math.random()*10);

                    Should be:

                    long duration=(long)(Math.random()*10);

                     

                     

                    Errata type: Typo| Page number: 169 | Errata date: 28 June 2013

                    16. Write a message to the console to indicate the finalization of the program.

                    System.out.println("Main: End");

                    System.out.printf("Main: End.\n");

                    Should delete the duplicate clause : System.out.printf("Main: End.\n");

                     

                     

                    Errata type: Typo| Page number: 170 | Errata date: 28 June 2013

                    otherwise it throws RejectedExecutionExeption.

                    Should be:

                    otherwise it throws RejectedExecutionException.

                     

                     

                    Errata type: Code | Page number: 180 | Errata date: 03 July 2013

                    invoke(ForkJoinTask task)

                    Should be:

                    T invoke(ForkJoinTask task)

                     

                     

                    Errata type: Typo | Page number: 182 | Errata date: 03 July 2013

                    Fill the array with strings. ...in the generated array.

                    Should be:

                    Fill the matrix with strings....in the generated matrix.

                     

                    Errata type: Typo | Page number: 200 | Errata date: 03 July 2013

                    Declare a list of objects parameterized with the ForkJoinTask class parameterized with the Integer class named List.

                    Should be:

                    Declare a list of objects parameterized with the ForkJoinTask class parameterized with the Integer class named tasks.

                     

                    Errata type: Typo | Page number: 202 | Errata date: 03 July 2013

                    19. For all the elements in the block of elements this task has to process

                    Should be:

                    19. For all the elements in the block of array this task has to process

                     

                    Errata type: Typo | Page number: 129 | Errata date: 03 July 2013

                    Use the executor created by the newCachedThreadPool() method only when you have a reasonable number of threads or when they have a short duration.

                    Should be:

                    Use the executor created by the newCachedThreadPool() method only when you have a reasonable number of threads or when tasks have a short duration.

                    Errata type: Code | Page number: 14

                    Bullet point 7: The following code:

                    try {
                    Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    e.printStackTrace();
                    }

                    Should be:

                    try { TimeUnit.SECONDS.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }

                     

                    Sample chapters

                    You can view our sample chapters and prefaces of this title on PacktLib or download sample chapters in PDF format.

                    Frequently bought together

                    Java 7 Concurrency Cookbook +    Microsoft Visual Studio LightSwitch Business Application Development =
                    50% Off
                    the second eBook
                    Price for both: $45.60

                    Buy both these recommended eBooks together and get 50% off the cheapest eBook.

                    What you will learn from this book

                    Master the basics of thread management and synchronization before diving into higher level concurrency tasks Get to grips with exciting new concurrency features of Java 7, including the Phaser Class and the Fork/Join Framework Successfully delegate thread management to executors Customize some of the most useful classes of the Java concurrency API with real-world examples Learn to use high-level Java utilities to manage synchronization between threads Get a sneak peek at using Eclipse and NetBeans for debugging concurrency code Avoid problems with data inconsistency by learning the data structures you have to use in concurrent applications Take advantage of a bonus appendix packed with tips that every programmer should consider when developing a concurrent application

                    In Detail

                    Java remains the global standard for developing various applications and enterprise software, and the launch of Java 7 brings with it exciting new capabilities for concurrent programming by way of the concurrency utilities enhancement. This allows developers to make the most of their applications with parallel task performance. "Java 7 Concurrency Cookbook" covers all elements of the Java concurrency API, providing essential recipes for taking advantage of the exciting new capabilities.On your computer, you can listen to music while you edit a Word document and read your emails, all at once! This is because your operating system allows the concurrency of tasks, much like the Java platform which offers various classes to execute concurrent tasks inside a Java program. "Java 7 Concurrency Cookbook" covers the most important features of the Java concurrency API, with special emphasis on the new capabilities of version 7. With each version, Java increases the available functionality to facilitate development of concurrent programs. This book covers the most important and useful mechanisms included in version 7 of the Java concurrency API, so you will be able to use them directly in your applications."Java 7 Concurrency Cookbook" includes recipes to enable you to achieve everything from the basic management of threads and tasks, to the new Fork /Join framework, through synchronization mechanisms between tasks, different types of concurrent tasks that Java can execute, data structures that must be used in concurrent applications and the classes of the library that can be customized.With the step-by-step examples in this book you’ll be able to apply the most important and useful features of the Java 7 concurrency API.

                    Approach

                    "Java 7 Concurrency Cookbook" is a practical Cookbook packed with real-world solutions. Intermediate–advanced level Java developers will learn from task-based recipes to use Java’s concurrent API to program thread safe solutions.

                    Who this book is for

                    If you are a Java developer who wants to take your knowledge of concurrent programming and multithreading further, as well as discover the new concurrency features of Java 7, then "Java 7 Concurrency Cookbook" is for you.You should already be comfortable with general Java development practices and a basic grasp of threads would be an advantage.

                    Code Download and Errata
                    Packt Anytime, Anywhere
                    Register Books
                    Print Upgrades
                    eBook Downloads
                    Video Support
                    Contact Us
                    Awards Voting Nominations Previous Winners
                    Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
                    Resources
                    Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software