Java Reference
In-Depth Information
}
} catch (ClassNotFoundException e) {}
}
}
Example 8.4.3.6-2. synchronized Methods
Click here to view code image
public class Box {
private Object boxContents;
public synchronized Object get() {
Object contents = boxContents;
boxContents = null;
return contents;
}
public synchronized boolean put(Object contents) {
if (boxContents != null) return false;
boxContents = contents;
return true;
}
}
This program defines a class which is designed for concurrent use. Each instance of
the class Box has an instance variable boxContents that can hold a reference to any ob-
ject.
You can put an object in a Box by invoking put , which returns false if the box is already
full. You can get something out of a Box by invoking get , which returns a null refer-
ence if the box is empty.
If put and get were not synchronized , and two threads were executing methods for the
same instance of Box at the same time, then the code could misbehave. It might, for
example, lose track of an object because two invocations to put occurred at the same
time.
8.4.4. Generic Methods
A method is generic if it declares one or more type variables (§ 4.4 ) .
These type variables are known as the type parameters of the method. The form of the type
parameter section of a generic method is identical to the type parameter section of a generic
class (§ 8.1.2 ) .
Search WWH ::




Custom Search