Java Reference
In-Depth Information
This exclusivity has nothing to do with other objects of the McBurgerPlace class. For exam-
ple, the McBurgerPlace on Fifth Street is free to make burgers, sell French fries, and so forth,
even if the McBurgerPlace on High Street is currently waxing the floor. Why shouldn't they?
What about dealing with an activity that does affect other objects? For example, what
about receiving the chiefExecutiveOfficer ? Obviously, you only want a single McBurgerPlace
to receive the chiefExecutiveOfficer at a given time: She can't be in two places at once. How
do you represent this exclusivity of access in Java? For that matter, how do you control access
to her? You don't want one store to interrupt her while she is in the middle of talking to
another store.
There are two steps in the solution to this dilemma. First, make sure that the
chiefExecutiveOfficer variable is static—that is, it exists only at the class level. You can
achieve this by using the keyword static when declaring the chiefExecutiveOfficer
variable at the class level:
private static Object ceo = new Object();
The second step is to synchronize the static method that accesses the chiefExecutive
Officer , like this:
public static synchronized Object receiveCeo (){
return ceo;
}
Because the method is static, this synchronization occurs at class level rather than at
instance level.
Locking Objects Directly
There is a second way to lock objects (both instance objects and class objects). You can synchro-
nize on the object you want to lock explicitly. For example, imagine that your McBurgerPlace
class has a getSoda method that requires exclusive control of the sodaFountain member vari-
able. You can lock the entire McBurgerPlace object, or you can lock just the sodaFountain
member variable:
public void getSodaEfficiently() {
synchronized (sodaFountain) {
//do Stuff
}
}
Locking a member variable object is like forcing only those people who want to use the
sodaFountain to wait while you are using the sodaFountain , as opposed to forcing everyone in
the entire store (including those who only want to purchase a burger) to wait.
Synchronizing a method is a form of locking an object—specifically, the this object. Syn-
chronizing a method is really just shorthand for synchronizing on the this reference object.
Thus, this code presented in Listing 4-2 is equivalent to the code presented in Listing 4-3.
Search WWH ::




Custom Search