3.10 Summary
In this chapter, we've introduced the
synchronized keyword of the Java language. This
keyword allows us to synchronize methods and blocks of code.
We've also examined the basic synchronization
classes provided by the Java class library — the
ReentrantLock class and the
Lock interface. These classes allow us to lock
objects across methods and to acquire and release the lock at will
based on external events. They also provide features such as testing
to see if the lock is available, placing timeouts on obtaining the
lock, or controlling the order on granting locks.
We've also looked at a common way of handling
synchronization of a single variable: the
volatile keyword.
Using the volatile keyword is typically easier
than setting up needed synchronization around a single variable.
This concludes our first look at synchronization. As you can tell, it
is one of the most important aspects of threaded programming. Without
these techniques, we would not be able to share data correctly
between the threads that we create. However, we've
just begun to look at how threads can share data. The simple
synchronization techniques of this chapter are a good start; in the
next chapter, we look at how threads can notify each other that data
has been changed.
3.10.1 Example Classes
Here are the class names and Ant targets for the examples in this
chapter:
|
Description
|
Main Java class
|
Ant target
|
|---|
|
Swing Type Tester with ScoreLabel
|
javathreads.examples.ch03.example1.SwingTypeTester
|
ch3-ex1
| |
ScoreLabel with explicit lock
|
javathreads.examples.ch03.example2.SwingTypeTester
|
ch3-ex2
| |
ScoreLabel with explicit locking at a small scope
|
javathreads.examples.ch03.example3.SwingTypeTester
|
ch3-ex3
| |
ScoreLabel with synchronized block locking
|
javathreads.examples.ch03.example4.SwingTypeTester
|
ch3-ex4
| |
ScoreLabel with nested locks
|
javathreads.examples.ch03.example5.SwingTypeTester
|
ch3-ex5
| |
Deadlocking Animation Canvas
|
javathreads.examples.ch03.example6.SwingTypeTester
|
ch3-ex6
| |
Deadlocking Animation Canvas (scope corrected)
|
javathreads.examples.ch03.example7.SwingTypeTester
|
ch3-ex7
| |
Deadlocking ScoreLabel
|
javathreads.examples.ch03.example8.SwingTypeTester
|
ch3-ex8
| |
Deadlocking ScoreLabel (deadlock corrected)
|
javathreads.examples.ch03.example9.SwingTypeTester
|
ch3-ex9
|
|