Java Reference
In-Depth Information
In this case, only one thread at a time in a process can call the getErrorMsg()
method in a particular instance of the ErrorMsg class. If other threads attempt to call
getErrorMsg() for a particular instance of ErrorMsg , the second thread will wait.
Another way to coordinate activities among threads is to define a synchroniza-
tion block of code. This is a block of code that has been explicitly marked to syn-
chronize on any object or static class member.
public class ErrorMsg {
DatabaseConnection myDB = new DatabaseConnection ()
public String getErrorMsg () {
if (ErrorMsgnotRead) {
synchronized (myDB.CONNECTION_SYNCH) {
// Read the database, and make sure only one instance of DatabaseConnection
// is doing it at a time. The CONNECTION_SYNCH static class member is
// used to synchronize all instances of DatabaseConnection.
...
}
}
}
}
Of course, it is up to the developer to make sure that all relevant access to this
object is also synchronized. Sometimes this technique is referred to as manual syn-
chronization.
Java 1.5 adds some additional thread management tools in the concurrency
utility library. One popular tool is the semaphore . Using a semaphore, a developer
can control access to any arbitrary block of code or resource. Think of a semaphore
as a type of check out/check in control applied to a defined set of permits. A thread
can ask for a permit (for example, permission to use a resource) using acquire() .
The thread will block until a permit is available. When a thread is done with the
permit, it returns it to the permission pool using release() . When a permission
pool has only one permit available, a semaphore can be used as a mutual exclusion
locking mechanism.
For example, a semaphore can be used to synchronize access to the output
stream (typically the console). A thread can ask for access to the console by calling
the acquire() or acquireUninterruptibly() method of an agreed-upon semaphore
object. As long as all threads use this same object, only one thread at a time will
get control to that object. The others will wait until the thread with control calls the
release() method.
Search WWH ::




Custom Search