8.4.3
Method Modifiers
CLASSES
has exactly the same effect as:
class BumpTest {
int count;
void bump() {
synchronized (this) {
count++;
}
}
static int classCount;
static void classBump() {
try {
synchronized (Class.forName("BumpTest")) {
classCount++;
}
} catch (ClassNotFoundException e) {
...
}
}
}
The more elaborate example:
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;
}
}
defines a class which is designed for concurrent use. Each instance of the class
Box
 has an instance variable
contents
 that can hold a reference to any object.
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 reference 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 misbe 
have. It might, for example, lose track of an object because two invocations to
put
occurred at the same time.
162






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

java hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Inexpensive Web Hosting  Jsp Web Hosting

Cheapest Web Hosting Jsp Hosting Cheap Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved