Java Concurrency In Practice Brian Gδetz Tim Peierls Joshua Bloch Joseph Bowbeer David Holmes Doug Lea Addison-Wesley Professional 1SBN-10:0-321-34960-1 1SBN-13:978-0-321-34960-6
Java Concurrency In Practice Brian Göetz Tim Peierls Joshua Bloch Joseph Bowbeer David Holmes Doug Lea AddisonͲWesley Professional ISBNͲ10: 0Ͳ321Ͳ34960Ͳ1 ISBNͲ13: 978Ͳ0Ͳ321Ͳ34960Ͳ6
Java Concurrency In Practice Index Index ii Preface xiii How to Use this Book 诚 Code Examples xiv Acknowledaments Chapter 1-Introduction 1 1.1.A(Very)Brief History of Concurrency 2 1.2.Benefits of Threads 3 1.2:1Exploiting Multiple processors 12:2 Simplicity of Modelina 3 3 1.2.3.Simplified Handling of Asvnchronous Events 1.2.4.More Responsive User Interfaces 1.3.Risks of Threads 5 1.3.1.Safety.Hazards. 1.3.2.Liveness Hazards. 、 1.3.3.Performance Hazards 1.4.Threads are Everywhere 8 Part l:Fundamentals 10 Chapter 2.Thread Safety 11 2.1.What is Thread Safety? 12 2.2.Atomicity. 13 2.3.40 cking.… 2.4.Guarding State with Locks 6 19 2.5.Liveness and Performance …20 Chapter 3.Sharing Objects 23 3-visibility 23 3.2.Publication and Escape 2 3.3..Thread Confinement... .…28 3.4.Immutability 31 3.5.Safe Publication 33 Chapter 4.Composing Objects 37 4.1.Designing a Thread-safe Class. 37 4.2:.Instance confinement 39 4.3.Delegating Thread Safety 42 4.4.Adding Functionality to Existina.Thread-safe.Classes. 47 4.5.Documentina Synchronization policies 49 Chapter 5.Building Blocks 51 5.1.Svnchronized Collections. .51 5.2.Concurrent Collections 54 5.3.Blocking Queues and the Producer-consumer Pattern.. 55 5.4.Blocking and Interruptible Methods 5.5.Svnchron.ie...… 0 5.6.Building an Efficient,Scalable Result Cache 64 Summary of Part 1 .59
ii Java Concurrency In Practice Index Index ii Preface xiii How to Use this Book xiii Code Examples xiv Acknowledgments xv Chapter 1 - Introduction 1 1.1. A (Very) Brief History of Concurrency 2 1.2. Benefits of Threads 3 1.2.1. Exploiting Multiple Processors 3 1.2.2. Simplicity of Modeling 3 1.2.3. Simplified Handling of Asynchronous Events 3 1.2.4. More Responsive User Interfaces 4 1.3. Risks of Threads 5 1.3.1. Safety Hazards 5 1.3.2. Liveness Hazards 6 1.3.3. Performance Hazards 6 1.4. Threads are Everywhere 8 Part I: Fundamentals 10 Chapter 2. Thread Safety 11 2.1. What is Thread Safety? 12 2.2. Atomicity 13 2.3. Locking 16 2.4. Guardin g State with Locks 19 2.5. Liveness and Performance 20 Chapter 3. Sharing Objects 23 3.1. Visibility 23 3.2. Publication and Escape 26 3.3. Thread Confinement 28 3.4. Immutability 31 3.5. Safe Publication 33 Chapter 4. Composing Objects 37 4.1. Designin g a Thread Ͳsafe Class 37 4.2. Instance Confinement 39 4.3. Delegating Thread Safety 41 4.4. Adding Functionality to Existing Thread Ͳsafe Classes 47 4.5. Documenting Synchronization Policies 49 Chapter 5. Building Blocks 51 5.1. Synchronized Collections 51 5.2. Concurrent Collections 54 5.3. Blocking Queues an d the Producer Ͳconsumer Pattern 56 5.4. Blocking and Interruptible Methods 59 5.5. Synchronizers 60 5.6. Building an Efficient, Scalable Result Cache 64 Summary of Part I 69
<Index Part ll:Structuring Concurrent Applications 71 Chapter 6.Task Execution 72 6.1.Executing Tasks in.Threads 72 6.2.The Executor Framework. 74 6.3..Finding Exploitable Parallelism. 78 Summary. 83 Chapter 7.Cancellation and Shutdown 85 7.1.Task Cancellation 7.2 Stopping a Thread-based Service 85 7.3..Handling Abnormal.Thread Termination.. 23 .100 7.4.JVM Shutdown 102 Summary ..103 Chapter 8.Applying Thread Pools 104 8.1.Implicit Couplings Between Tasks and Execution Policies 104 ■■■■ 8.2.Sizing Thread Pools. .105 8.3.Configuring ThreadPoolExecutor ...1Q5 8.4.Extendina ThreadPoolExecutor. 111 8.5.Parallelizing Recursive Algorithms. .112 115 Chapter 2 GUL Applications 117 9.1.Why are GUls Single-threaded? 117 9.2:Short-running GUl Tasks... .…119 9.3.Long-runnina Gu Tasks 122 9.4.Shared Data Models.. ■■■ .123 9.5.Other Forms of Single-threaded Subsystems. 125 Summary......... .125 Partll:Liveness,Performance,and Testing 12Z Chapter 10.Avoiding Liveness Hazards 128 10.1.Deadlock .128 10.2.Avoiding and Diagnosing Deadlocks 133 10.3.Other Liveness Hazards 135 .136 Chapter 11.Performance and Scalability 137 11.1.Thinking about Performance. 137 11.2:Amdah!'s Law 139 11.3.Costs Introduced by Threads .142 11.4.Reducing Lock Contention. .144 ■■■■■■■ 11.5.Example:Comparing Map Performance. .150 11.6.Reducing Context Switch Overhead. 151 Summary 152 Chapter 12.Testing Concurrent Programs 153 12.1.Testing for Correctness... .153 12.2.Testing for Performance.. .160 12.3.Avoidina Performance Testing Pitfalls 165 12.4.Complementary Testing Approaches .167 Summary. 169 Part IV:Adyanced Topics 170 Chapter 13-Explicit Locks 171 13.1.Lock and Reentrantlock... .171 13.2.Performance Considerations .174 13.3.Fairnes5.… 175
<Index iii Part II: Structuring Concurrent Applications 71 Chapter 6. Task Execution 72 6.1. Executing Tasks in Threads 72 6.2. Th e Executor Framework 74 6.3. Finding Exploitable Parallelism 78 Summary 83 Chapter 7. Cancellation and Shutdown 85 7.1. Task Cancellation 85 7.2. Stopping a Thread Ͳbased Service 93 7.3. Handling Abnormal Thread Termination 100 7.4. JVM Shutdown 102 Summary 103 Chapter 8. Applying Thread Pools 104 8.1. Implicit Couplings Between Tasks and Execution Policies 104 8.2. Sizing Thread Pools 105 8.3. Configuring ThreadPoolExecutor 106 8.4. Extending ThreadPoolExecutor 111 8.5. Parallelizing Recursive Algorithms 112 Summary 116 Chapter 9. GUI Applications 117 9.1. Why are GUI s Single Ͳthreaded? 117 9.2. Short Ͳ running GUI Tasks 119 9.3. Long Ͳrunning GU I Tasks 121 9.4. Shared Data Models 123 9.5. Other Forms of Single Ͳthreaded Subsystems 125 Summary 126 Part III: Liveness, Performance, and Testing 127 Chapter 10. Avoiding Liveness Hazards 128 10.1. Deadlock 128 10.2. Avoiding and Diagnosing Deadlocks 133 10.3. Other Liveness Hazards 135 Summary 136 Chapter 11. Performance and Scalability 137 11.1. Thinking about Performance 137 11.2. Amdahl's Law 139 11.3. Costs Introduced by Threads 142 11.4. Reducing Lock Contention 144 11.5. Example: Comparing Map Performance 150 11.6. Reducing Context Switch Overhead 151 Summary 152 Chapter 12. Testing Concurrent Programs 153 12.1. Testing for Correctness 153 12.2. Testing for Performance 160 12.3. Avoiding Performanc e Testing Pitfalls 165 12.4. Complementary Testing Approaches 167 Summary 169 Part IV: Advanced Topics 170 Chapter 13 - Explicit Locks 171 13.1. Lock an d ReentrantLock 171 13.2. Performance Considerations 174 13.3. Fairness 175
iv Java Concurrency In Practice 13.4..Choosing.Between.Synchronized and ReentrantLock 175 135Read-writeLocks 175 Syma以.… 17 Chapter 14-Building Custom Synchronizers 179 14.1.Managing State Dependence 179 14.2.Using Condition Queues.. .183 14.3.Explicit Condition Objects 14.4.Anatomy of a Synchronizer... 188 189 14.5.AbstractQueuedSynchronizer. .190 14.6.AOS.in Jlava.util.concurrent Synchronizer Classes. .192 Summary. 194 Chapter 15.Atomic Variables and Non-blocking Synchronization 195 15.1.Disadvantages of Locking 195 15.2.Hardware Support for Concurrency. 195 15.3.Atomic Variable Classes. 198 15.4.Non-blocking Algorithms 201 Summa以.… 2Q5 Chapter 16.The Java Memory Model 207 16.1.What is a Memory Model,and Why would Want One? 207 16.2 Publication 211 225 Appendix A.Annotations for Concurrency 216 A1..Class Annotations. 216 A.2..Field and Method Annotations. 215 Bibliography 21Z
iv Java Concurrency In Practice 13.4. Choosing Between Synchronized and ReentrantLock 176 13.5. ReadͲwrite Locks 176 Summary 178 Chapter 14 - Building Custom Synchronizers 179 14.1. Managing State Dependence 179 14.2. Using Condition Queues 183 14.3. Explicit Condition Objects 188 14.4. Anatomy of a Synchronizer 189 14.5. AbstractQueuedSynchronizer 190 14.6. AQS in Java.util.concurrent Synchronizer Classes 192 Summary 194 Chapter 15. Atomic Variables and Non-blocking Synchronization 195 15.1. Disadvantages of Locking 195 15.2. Hardware Support for Concurrency 196 15.3. Atomic Variable Classes 198 15.4. NonͲblocking Algorithms 201 Summary 206 Chapter 16. The Java Memory Model 207 16.1. What is a Memory Model, and Why would I Want One? 207 16.2. Publication 211 Summary 215 Appendix A. Annotations for Concurrency 216 A.1. Class Annotations 216 A.2. Field and Method Annotations 216 Bibliography 217
1BListing and Image Index Listing and Image Index Preface Y Listing 1.Bad Way to Sort a List.Don't Do this. xiv Listing 2.Less than Optimal Way to Sort a List. y Chapter 1.Introduction 11 Listing 1.1.Non-thread-safe Sequence Generator 5 Figure 1.1.Unlucky Execution of Unsafesequence.Nextvalue. 5 Listing 1.2.Thread-safe Sequence Generator. 6 Chapter 2.Thread Safety 11 Listing 2.1.A Stateless Servlet. 13 Listing 2.2.Servlet that Counts Requests without the Necessary Synchronization.Don't Do this. 14 Listing 2.3.Race Condition in Lazy Initialization.Don't Do this. 15 Listing 2.4.Servlet that Counts Requests Using Atomi cLonq. 16 Listing 2.5.Servlet that Attempts to Cache its Last Result without Adequate Atomicity.Don't Do this. 17 Listing 2.6.Servlet that Caches Last Result,But with Unacceptably Poor Concurrency.Don't Do this. 18 Listing 2.7.Code that would Deadlock if Intrinsic Locks were Not Reentrant. 18 Figure 2.1.Poor Concurrency of SynchronizedFactorizer. 21 Listing 2.8.Servlet that Caches its Last Request and Result. 21 Chapter 3.Sharing Objects 23 Listing 3.1.Sharing Variables without Synchronization.Don't Do this. 23 Listing 3.2.Non-thread-safe Mutable Integer Holder. 24 Listing 3.3.Thread-safe Mutable Integer Holder. 24 Figure 3.1.Visibility Guarantees for Synchronization. 25 Listing 3.4.Counting Sheep. 26 Listing 3.5.Publishing an Object. 27 Listing 3.6.Allowing Internal Mutable State to Escape.Don't Do this. 21 Listing 3.7.Implicitly Allowing the this Reference to Escape.Don't Do this. 28 Listing 3.8.Using a Factory Method to Prevent the this Reference from Escaping During Construction. 28 Listing 3.9.Thread Confinement of Local Primitive and Reference Variables. 30 Listing 3.10.Using ThreadLocal to Ensure thread Confinement. 30 Listing 3.11.Immutable Class Built Out of Mutable Underlying Objects 32 Listing 3.12.Immutable Holder for Caching a Number and its Factors. 33 Listing 3.13.Caching the Last Result Using a Volatile Reference to an Immutable Holder Object. 33 Listing 3.14.Publishing an Object without Adequate Synchronization.Don't Do this. 33
1BListing and Image Index v Listing and Image Index Preface v Listing 1. Bad Way to Sort a List. Don't Do this. xiv Listing 2. Less than Optimal Way to Sort a List. xv Chapter 1. Introduction 11 Listing 1.1. NonͲthreadͲsafe Sequence Generator. 5 Figure 1.1. Unlucky Execution of UnsafeSequence.Nextvalue. 5 Listing 1.2. ThreadͲsafe Sequence Generator. 6 Chapter 2. Thread Safety 11 Listing 2.1. A Stateless Servlet. 13 Listing 2.2. Servlet that Counts Requests without the Necessary Synchronization. Don't Do this. 14 Listing 2.3. Race Condition in Lazy Initialization. Don't Do this. 15 Listing 2.4. Servlet that Counts Requests Using AtomicLong. 16 Listing 2.5. Servlet that Attempts to Cache its Last Result without Adequate Atomicity. Don't Do this. 17 Listing 2.6. Servlet that Caches Last Result, But with Unacceptably Poor Concurrency. Don't Do this. 18 Listing 2.7. Code that would Deadlock if Intrinsic Locks were Not Reentrant. 18 Figure 2.1. Poor Concurrency of SynchronizedFactorizer. 21 Listing 2.8. Servlet that Caches its Last Request and Result. 21 Chapter 3. Sharing Objects 23 Listing 3.1. Sharing Variables without Synchronization. Don't Do this. 23 Listing 3.2. NonͲthreadͲsafe Mutable Integer Holder. 24 Listing 3.3. ThreadͲsafe Mutable Integer Holder. 24 Figure 3.1. Visibility Guarantees for Synchronization. 25 Listing 3.4. Counting Sheep. 26 Listing 3.5. Publishing an Object. 27 Listing 3.6. Allowing Internal Mutable State to Escape. Don't Do this. 27 Listing 3.7. Implicitly Allowing the this Reference to Escape. Don't Do this. 28 Listing 3.8. Using a Factory Method to Prevent the this Reference from Escaping During Construction. 28 Listing 3.9. Thread Confinement of Local Primitive and Reference Variables. 30 Listing 3.10. Using ThreadLocal to Ensure thread Confinement. 30 Listing 3.11. Immutable Class Built Out of Mutable Underlying Objects. 32 Listing 3.12. Immutable Holder for Caching a Number and its Factors. 33 Listing 3.13. Caching the Last Result Using a Volatile Reference to an Immutable Holder Object. 33 Listing 3.14. Publishing an Object without Adequate Synchronization. Don't Do this. 33