If you have worked with synchronization when using other languages, such as C or C++,
you know that it can be a bit tricky to use. This is because these languages do not, themselves,
support synchronization. Instead, to synchronize threads, your programs need to utilize
operating system primitives. Fortunately, because Java implements synchronization through
language elements, most of the complexity associated with synchronization has been
eliminated.
You can synchronize your code in either of two ways. Both involve the use of the
synchronized keyword, and both are examined here.
Using Synchronized Methods
Synchronization is easy in Java, because all objects have their own implicit monitor associated
with them. To enter an object's monitor, just call a method that has been modified with the
synchronized keyword. While a thread is inside a synchronized method, all other threads
that try to call it (or any other synchronized method) on the same instance have to wait. To
exit the monitor and relinquish control of the object to the next waiting thread, the owner of
the monitor simply returns from the synchronized method.
To understand the need for synchronization, let's begin with a simple example that does
not use it--but should. The following program has three simple classes. The first one, Callme,
has a single method named call( ). The call( ) method takes a String parameter called msg.
This method tries to print the msg string inside of square brackets. The interesting thing
to notice is that after call( ) prints the opening bracket and the msg string, it calls Thread
.sleep(1000), which pauses the current thread for one second.
The constructor of the next class, Caller, takes a reference to an instance of the Callme
class and a String, which are stored in target and msg, respectively. The constructor also creates
a new thread that will call this object's run( ) method. The thread is started immediately. The
run( ) method of Caller calls the call( ) method on the target instance of Callme, passing in
the msg string. Finally, the Synch class starts by creating a single instance of Callme, and
three instances of Caller, each with a unique message string. The same instance of Callme
is passed to each Caller.
// This program is not synchronized.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home