. . . .
The class object itself is a subclass of Object; hence it too has a mutex and wait set. This mutex
can be used to protect static data. It is used for static synchronized methods (see Code Example 6-
7). The class lock may be used to protect class internals during instance creation, but this should
not be an issue unless you're holding onto it for unusually long periods of time. In that case you
may wish to use a different object (Code Example 6-8) to protect your static variables (probably
Example 6-7 Static Synchronized Methods Also Use the Class Lock
public class Foo {
static int count = 0;
static public synchronized void inc(int i) {
count = count + i;
Example 6-8 You May Use an Unrelated Object to Protect Static Data
public class Foo {
static int count = 0;
static Object o = new Object();
public void inc(int i) {
synchronized (o) {
count = count + i;
Notice that in Code Example 6-9 we use Foo.class to obtain the class object for Foo. Should
you later define Bar, which subclasses Foo, a call to will of course increment the
same count variable as (static variables are inherited by subclasses) and the lock
from the Foo class will be locked, not the lock from Bar. This is, of course, what we want. If we
had called getClass() instead of Foo.class, we would have locked the lock for Bar. That
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks