站内搜索: 请输入搜索关键词
当前页面: 图书首页 > Java Concurrency in Practice

Listings - Java Concurrency in Practice

Previous Page
Next Page

Listings


[Pages xiii - xvi]

1

Bad way to sort a list. Don't do this.

xix

2

Less than optimal way to sort a list

xx

1.1

Non-thread-safe sequence generator

6

1.2

Thread-safe sequence generator

7

2.1

A stateless servlet

18

2.2

Servlet that counts requests without the necessary synchronization. Don't do this.

19

2.3

Race condition in lazy initialization. Don't do this.

21

2.4

Servlet that counts requests using AtomicLong

23

2.5

Servlet that attempts to cache its last result without adequate atomicity. Don't do this.

24

2.6

Servlet that caches last result, but with unnacceptably poor concurrency. Don't do this.

26

2.7

Code that would deadlock if intrinsic locks were not reentrant

27

2.8

Servlet that caches its last request and result

31

3.1

Sharing variables without synchronization. Don't do this.

34

3.2

Non-thread-safe mutable integer holder

36

3.3

Thread-safe mutable integer holder

36

3.4

Counting sheep

39

3.5

Publishing an object

40

3.6

Allowing internal mutable state to escape. Don't do this.

40

3.7

Implicitly allowing the this reference to escape. Don't do this.

41

3.8

Using a factory method to prevent the this reference from escaping during construction

42

3.9

Thread confinement of local primitive and reference variables

44

3.10

Using ThreadLocal to ensure thread confinement

45

3.11

Immutable class built out of mutable underlying objects

47

3.12

Immutable holder for caching a number and its factors

49

3.13

Caching the last result using a volatile reference to an immutable holder object

50

3.14

Publishing an object without adequate synchronization. Don't do this.

50

3.15

Class at risk of failure if not properly published

51

4.1

Simple thread-safe counter using the Java monitor pattern

56

4.2

Using confinement to ensure thread safety

59

4.3

Guarding state with a private lock

61

4.4

Monitor-based vehicle tracker implementation

63

4.5

Mutable point class similar to java.awt.Point

64

4.6

Immutable Point class used by DelegatingVehicleTracker

64

4.7

Delegating thread safety to a ConcurrentHashMap

65

4.8

Returning a static copy of the location set instead of a "live" one

66

4.9

Delegating thread safety to multiple underlying state variables

66

4.10

Number range class that does not sufficiently protect its invariants. Don't do this.

67

4.11

Thread-safe mutable point class

69

4.12

Vehicle tracker that safely publishes underlying state

70

4.13

Extending Vector to have a put-if-absent method

72

4.14

Non-thread-safe attempt to implement put-if-absent. Don't do this.

72

4.15

Implementing put-if-absent with client-side locking

73

4.16

Implementing put-if-absent using composition

74

5.1

Compound actions on a Vector that may produce confusing results

80

5.2

Compound actions on Vector using client-side locking

81

5.3

Iteration that may throw ArrayIndexOutOfBoundsException

81

5.4

Iteration with client-side locking

82

5.5

Iterating a List with an Iterator

82

5.6

Iteration hidden within string concatenation. Don't do this.

84

5.7

ConcurrentMap interface

87

5.8

Producer and consumer tasks in a desktop search application

91

5.9

Starting the desktop search

92

5.10

Restoring the interrupted status so as not to swallow the interrupt

94

5.11

Using CountDownLatch for starting and stopping threads in timing tests

96

5.12

Using FutureTask to preload data that is needed later

97

5.13

Coercing an unchecked THRowable to a RuntimeException

98

5.14

Using Semaphore to bound a collection

100

5.15

Coordinating computation in a cellular automaton with Cyclic-Barrier

102

5.16

Initial cache attempt using HashMap and synchronization

103

5.17

Replacing HashMap with ConcurrentHashMap

105

5.18

Memoizing wrapper using FutureTask

106

5.19

Final implementation of Memoizer

108

5.20

Factorizing servlet that caches results using Memoizer

109

6.1

Sequential web server

114

6.2

Web server that starts a new thread for each request

115

6.3

Executor interface

117

6.4

Web server using a thread pool

118

6.5

Executor that starts a new thread for each task

118

6.6

Executor that executes tasks synchronously in the calling thread

119

6.7

Lifecycle methods in ExecutorService

121

6.8

Web server with shutdown support

122

6.9

Class illustrating confusing Timer behavior

124

6.10

Rendering page elements sequentially

125

6.11

Callable and Future interfaces

126

6.12

Default implementation of newTaskFor in ThreadPoolExecutor

126

6.13

Waiting for image download with Future

128

6.14

QueueingFuture class used by ExecutorCompletionService

129

6.15

Using CompletionService to render page elements as they become available

130

6.16

Fetching an advertisement with a time budget

132

6.17

Requesting travel quotes under a time budget

134

7.1

Using a volatile field to hold cancellation state

137

7.2

Generating a second' sworth of prime numbers

137

7.3

Unreliable cancellation that can leave producers stuck in a blocking operation. Don't do this.

139

7.4

Interruption methods in Thread

139

7.5

Using interruption for cancellation

141

7.6

Propagating InterruptedException to callers

143

7.7

Noncancelable task that restores interruption before exit

144

7.8

Scheduling an interrupt on a borrowed thread. Don't do this.

145

7.9

Interrupting a task in a dedicated thread

146

7.10

Cancelling a task using Future

147

7.11

Encapsulating nonstandard cancellation in a THRead by overriding interrupt

149

7.12

Encapsulating nonstandard cancellation in a task with newTaskFor

151

7.13

Producer-consumer logging service with no shutdown support

152

7.14

Unreliable way to add shutdown support to the logging service

153

7.15

Adding reliable cancellation to LogWriter

154

7.16

Logging service that uses an ExecutorService

155

7.17

Shutdown with poison pill

156

7.18

Producer thread for IndexingService

157

7.19

Consumer thread for IndexingService

157

7.20

Using a private Executor whose lifetime is bounded by a method call

158

7.21

ExecutorService that keeps track of cancelled tasks after shutdown

159

7.22

Using trackingExecutorService to save unfinished tasks for later execution

160

7.23

Typical thread-pool worker thread structure

162

7.24

UncaughtExceptionHandler interface

163

7.25

UncaughtExceptionHandler that logs the exception

163

7.26

Registering a shutdown hook to stop the logging service

165

8.1

Task that deadlocks in a single-threaded Executor. Don't do this.

169

8.2

General constructor for ThreadPoolExecutor

172

8.3

Creating a fixed-sized thread pool with a bounded queue and the caller-runs saturation policy

175

8.4

Using a Semaphore to throttle task submission

176

8.5

THReadFactory interface

176

8.6

Custom thread factory

177

8.7

Custom thread base class

178

8.8

Modifying an Executor created with the standard factories

179

8.9

Thread pool extended with logging and timing

180

8.10

Transforming sequential execution into parallel execution

181

8.11

Transforming sequential tail-recursion into parallelized recursion

182

8.12

Waiting for results to be calculated in parallel

182

8.13

Abstraction for puzzles like the "sliding blocks puzzle"

183

8.14

Link node for the puzzle solver framework

184

8.15

Sequential puzzle solver

185

8.16

Concurrent version of puzzle solver

186

8.17

Result-bearing latch used by ConcurrentPuzzleSolver

187

8.18

Solver that recognizes when no solution exists

188

9.1

Implementing SwingUtilities using an Executor

193

9.2

Executor built atop SwingUtilities

194

9.3

Simple event listener

194

9.4

Binding a long-running task to a visual component

196

9.5

Long-running task with user feedback

196

9.6

Cancelling a long-running task

197

9.7

Background task class supporting cancellation, completion notification, and progress notification

199

9.8

Initiating a long-running, cancellable task with BackgroundTask. .

200

10.1

Simple lock-ordering deadlock. Don't do this.

207

10.2

Dynamic lock-ordering deadlock. Don't do this.

208

10.3

Inducing a lock ordering to avoid deadlock

209

10.4

Driver loop that induces deadlock under typical conditions

210

10.5

Lock-ordering deadlock between cooperating objects. Don't do this.

212

10.6

Using open calls to avoiding deadlock between cooperating objects

214

10.7

Portion of thread dump after deadlock

217

11.1

Serialized access to a task queue

227

11.2

Synchronization that has no effect. Don't do this.

230

11.3

Candidate for lock elision

231

11.4

Holding a lock longer than necessary

233

11.5

Reducing lock duration

234

11.6

Candidate for lock splitting

236

11.7

ServerStatus refactored to use split locks

236

11.8

Hash-based map using lock striping

238

12.1

Bounded buffer using Semaphore

249

12.2

Basic unit tests for BoundedBuffer

250

12.3

Testing blocking and responsiveness to interruption

252

12.4

Medium-quality random number generator suitable for testing

253

12.5

Producer-consumer test program for BoundedBuffer

255

12.6

Producer and consumer classes used in PutTakeTest

256

12.7

Testing for resource leaks

258

12.8

Thread factory for testing ThreadPoolExecutor

258

12.9

Test method to verify thread pool expansion

259

12.10

Using Thread.yield to generate more interleavings

260

12.11

Barrier-based timer

261

12.12

Testing with a barrier-based timer

262

12.13

Driver program for TimedPutTakeTest

262

13.1

Lock interface

277

13.2

Guarding object state using ReentrantLock

278

13.3

Avoiding lock-ordering deadlock using TRyLock

280

13.4

Locking with a time budget

281

13.5

Interruptible lock acquisition

281

13.6

ReadWriteLock interface

286

13.7

Wrapping a Map with a read-write lock

288

14.1

Structure of blocking state-dependent actions

292

14.2

Base class for bounded buffer implementations

293

14.3

Bounded buffer that balks when preconditions are not met

294

14.4

Client logic for calling GrumpyBoundedBuffer

294

14.5

Bounded buffer using crude blocking

296

14.6

Bounded buffer using condition queues

298

14.7

Canonical form for state-dependent methods

301

14.8

Using conditional notification in BoundedBuffer.put

304

14.9

Recloseable gate using wait and notifyAll

305

14.10

Condition interface

307

14.11

Bounded buffer using explicit condition variables

309

14.12

Counting semaphore implemented using Lock

310

14.13

Canonical forms for acquisition and release in AQS

312

14.14

Binary latch using AbstractQueuedSynchronizer

313

14.15

TRyAcquire implementation from nonfair ReentrantLock

315

14.16

tryAcquireShared and tryReleaseShared from Semaphore

316

15.1

Simulated CAS operation

322

15.2

Nonblocking counter using CAS

323

15.3

Preserving multivariable invariants using CAS

326

15.4

Random number generator using ReentrantLock

327

15.5

Random number generator using AtomicInteger

327

15.6

Nonblocking stack using Treiber's algorithm (Treiber, 1986)

331

15.7

Insertion in the Michael-Scott nonblocking queue algorithm (Michael and Scott, 1996)

334

15.8

Using atomic field updaters in ConcurrentLinkedQueue

335

16.1

Insufficiently synchronized program that can have surprising results. Don't do this.

340

16.2

Inner class of FutureTask illustrating synchronization piggybacking

343

16.3

Unsafe lazy initialization. Don't do this.

345

16.4

Thread-safe lazy initialization

347

16.5

Eager initialization

347

16.6

Lazy initialization holder class idiom

348

16.7

Double-checked-locking antipattern. Don't do this.

349

16.8

Initialization safety for immutable objects

350



Previous Page
Next Page