Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Listings

Listings

1Bad way to sort a list. Don’t do this.xix
2Less than optimal way to sort a listxx
1.1Non-thread-safe sequence generator6
1.2Thread-safe sequence generator7
2.1A stateless servlet18
2.2Servlet that counts requests without the necessary synchronization. Don’t do this.19
2.3Race condition in lazy initialization. Don’t do this.21
2.4Servlet that counts requests using AtomicLong23
2.5Servlet that attempts to cache its last result without adequate atomicity. Don’t do this.24
2.6Servlet that caches last result, but with unnacceptably poor concurrency. Don’t do this.26
2.7Code that would deadlock if intrinsic locks were not reentrant27
2.8Servlet that caches its last request and result31
3.1Sharing variables without synchronization. Don’t do this.34
3.2Non-thread-safe mutable integer holder36
3.3Thread-safe mutable integer holder36
3.4Counting sheep39
3.5Publishing an object40
3.6Allowing internal mutable state to escape. Don’t do this.40
3.7Implicitly allowing the this reference to escape. Don’t do this.41
3.8Using a factory method to prevent the this reference from escaping during construction42
3.9Thread confinement of local primitive and reference variables44
3.10Using ThreadLocal to ensure thread confinement45
3.11Immutable class built out of mutable underlying objects47
3.12Immutable holder for caching a number and its factors49
3.13Caching the last result using a volatile reference to an immutable holder object50
3.14Publishing an object without adequate synchronization. Don’t do this.50
3.15Class at risk of failure if not properly published51
4.1Simple thread-safe counter using the Java monitor pattern56
4.2Using confinement to ensure thread safety59
4.3Guarding state with a private lock61
4.4Monitor-based vehicle tracker implementation63
4.5Mutable point class similar to java.awt.Point64
4.6Immutable Point class used by DelegatingVehicleTracker64
4.7Delegating thread safety to a ConcurrentHashMap65
4.8Returning a static copy of the location set instead of a “live” one66
4.9Delegating thread safety to multiple underlying state variables66
4.10Number range class that does not sufficiently protect its invariants. Don’t do this.67
4.11Thread-safe mutable point class69
4.12Vehicle tracker that safely publishes underlying state70
4.13Extending Vector to have a put-if-absent method72
4.14Non-thread-safe attempt to implement put-if-absent. Don’t do this.72
4.15Implementing put-if-absent with client-side locking73
4.16Implementing put-if-absent using composition74
5.1Compound actions on a Vector that may produce confusing results80
5.2Compound actions on Vector using client-side locking81
5.3Iteration that may throw ArrayIndexOutOfBoundsException81
5.4Iteration with client-side locking82
5.5Iterating a List with an Iterator82
5.6Iteration hidden within string concatenation. Don’t do this.84
5.7ConcurrentMap interface87
5.8Producer and consumer tasks in a desktop search application91
5.9Starting the desktop search92
5.10Restoring the interrupted status so as not to swallow the interrupt94
5.11Using CountDownLatch for starting and stopping threads in timing tests96
5.12Using FutureTask to preload data that is needed later97
5.13Coercing an unchecked Throwable to a RuntimeException98
5.14Using Semaphore to bound a collection100
5.15Coordinating computation in a cellular automaton with Cyclic-Barrier102
5.16Initial cache attempt using HashMap and synchronization103
5.17Replacing HashMap with ConcurrentHashMap105
5.18Memoizing wrapper using FutureTask106
5.19Final implementation of Memoizer108
5.20Factorizing servlet that caches results using Memoizer109
6.1Sequential web server114
6.2Web server that starts a new thread for each request115
6.3Executor interface117
6.4Web server using a thread pool118
6.5Executor that starts a new thread for each task118
6.6Executor that executes tasks synchronously in the calling thread119
6.7Lifecycle methods in ExecutorService121
6.8Web server with shutdown support122
6.9Class illustrating confusing Timer behavior124
6.10Rendering page elements sequentially125
6.11Callable and Future interfaces126
6.12Default implementation of newTaskFor in ThreadPoolExecutor126
6.13Waiting for image download with Future128
6.14QueueingFuture class used by ExecutorCompletionService129
6.15Using CompletionService to render page elements as they become available130
6.16Fetching an advertisement with a time budget132
6.17Requesting travel quotes under a time budget134
7.1Using a volatile field to hold cancellation state137
7.2Generating a second’ sworth of prime numbers137
7.3Unreliable cancellation that can leave producers stuck in a blocking operation. Don’t do this.139
7.4Interruption methods in Thread139
7.5Using interruption for cancellation141
7.6Propagating InterruptedException to callers143
7.7Noncancelable task that restores interruption before exit144
7.8Scheduling an interrupt on a borrowed thread. Don’t do this.145
7.9Interrupting a task in a dedicated thread146
7.10Cancelling a task using Future147
7.11Encapsulating nonstandard cancellation in a Thread by overriding interrupt149
7.12Encapsulating nonstandard cancellation in a task with newTaskFor151
7.13Producer-consumer logging service with no shutdown support152
7.14Unreliable way to add shutdown support to the logging service153
7.15Adding reliable cancellation to LogWriter154
7.16Logging service that uses an ExecutorService155
7.17Shutdown with poison pill156
7.18Producer thread for IndexingService157
7.19Consumer thread for IndexingService157
7.20Using a private Executor whose lifetime is bounded by a method call158
7.21ExecutorService that keeps track of cancelled tasks after shutdown159
7.22Using TrackingExecutorService to save unfinished tasks for later execution160
7.23Typical thread-pool worker thread structure162
7.24UncaughtExceptionHandler interface163
7.25UncaughtExceptionHandler that logs the exception163
7.26Registering a shutdown hook to stop the logging service165
8.1Task that deadlocks in a single-threaded Executor. Don’t do this.169
8.2General constructor for ThreadPoolExecutor172
8.3Creating a fixed-sized thread pool with a bounded queue and the caller-runs saturation policy175
8.4Using a Semaphore to throttle task submission176
8.5ThreadFactory interface176
8.6Custom thread factory177
8.7Custom thread base class178
8.8Modifying an Executor created with the standard factories179
8.9Thread pool extended with logging and timing180
8.10Transforming sequential execution into parallel execution181
8.11Transforming sequential tail-recursion into parallelized recursion182
8.12Waiting for results to be calculated in parallel182
8.13Abstraction for puzzles like the “sliding blocks puzzle”183
8.14Link node for the puzzle solver framework184
8.15Sequential puzzle solver185
8.16Concurrent version of puzzle solver186
8.17Result-bearing latch used by ConcurrentPuzzleSolver187
8.18Solver that recognizes when no solution exists188
9.1Implementing SwingUtilities using an Executor193
9.2Executor built atop SwingUtilities194
9.3Simple event listener194
9.4Binding a long-running task to a visual component196
9.5Long-running task with user feedback196
9.6Cancelling a long-running task197
9.7Background task class supporting cancellation, completion notification, and progress notification199
9.8Initiating a long-running, cancellable task with BackgroundTask. .200
10.1Simple lock-ordering deadlock. Don’t do this.207
10.2Dynamic lock-ordering deadlock. Don’t do this.208
10.3Inducing a lock ordering to avoid deadlock209
10.4Driver loop that induces deadlock under typical conditions210
10.5Lock-ordering deadlock between cooperating objects. Don’t do this.212
10.6Using open calls to avoiding deadlock between cooperating objects214
10.7Portion of thread dump after deadlock217
11.1Serialized access to a task queue227
11.2Synchronization that has no effect. Don’t do this.230
11.3Candidate for lock elision231
11.4Holding a lock longer than necessary233
11.5Reducing lock duration234
11.6Candidate for lock splitting236
11.7ServerStatus refactored to use split locks236
11.8Hash-based map using lock striping238
12.1Bounded buffer using Semaphore249
12.2Basic unit tests for BoundedBuffer250
12.3Testing blocking and responsiveness to interruption252
12.4Medium-quality random number generator suitable for testing253
12.5Producer-consumer test program for BoundedBuffer255
12.6Producer and consumer classes used in PutTakeTest256
12.7Testing for resource leaks258
12.8Thread factory for testing ThreadPoolExecutor258
12.9Test method to verify thread pool expansion259
12.10Using Thread.yield to generate more interleavings260
12.11Barrier-based timer261
12.12Testing with a barrier-based timer262
12.13Driver program for TimedPutTakeTest262
13.1Lock interface277
13.2Guarding object state using ReentrantLock278
13.3Avoiding lock-ordering deadlock using tryLock280
13.4Locking with a time budget281
13.5Interruptible lock acquisition281
13.6ReadWriteLock interface286
13.7Wrapping a Map with a read-write lock288
14.1Structure of blocking state-dependent actions292
14.2Base class for bounded buffer implementations293
14.3Bounded buffer that balks when preconditions are not met294
14.4Client logic for calling GrumpyBoundedBuffer294
14.5Bounded buffer using crude blocking296
14.6Bounded buffer using condition queues298
14.7Canonical form for state-dependent methods301
14.8Using conditional notification in BoundedBuffer.put304
14.9Recloseable gate using wait and notifyAll305
14.10Condition interface307
14.11Bounded buffer using explicit condition variables309
14.12Counting semaphore implemented using Lock310
14.13Canonical forms for acquisition and release in AQS312
14.14Binary latch using AbstractQueuedSynchronizer313
14.15tryAcquire implementation from nonfair ReentrantLock315
14.16tryAcquireShared and tryReleaseShared from Semaphore316
15.1Simulated CAS operation322
15.2Nonblocking counter using CAS323
15.3Preserving multivariable invariants using CAS326
15.4Random number generator using ReentrantLock327
15.5Random number generator using AtomicInteger327
15.6Nonblocking stack using Treiber’s algorithm (Treiber, 1986)331
15.7Insertion in the Michael-Scott nonblocking queue algorithm (Michael and Scott, 1996)334
15.8Using atomic field updaters in ConcurrentLinkedQueue335
16.1Insufficiently synchronized program that can have surprising results. Don’t do this.340
16.2Inner class of FutureTask illustrating synchronization piggybacking343
16.3Unsafe lazy initialization. Don’t do this.345
16.4Thread-safe lazy initialization347
16.5Eager initialization347
16.6Lazy initialization holder class idiom348
16.7Double-checked-locking antipattern. Don’t do this.349
16.8Initialization safety for immutable objects350