Master-Slave

Problem

A graphical user interface needs to listen for user commands even while the last command is being executed. For example, the next command could be to cancel the previous one.

A server needs to listen for client requests even while it is processing previous requests. Failure to do so could result in frustrating service denials.

Solution

An object contains variables and is able to execute methods. However, all objects share a virtual machine which they use to execute the individual instructions in their methods.

By contrast, an active object has its own virtual machine. In UML a class of active objects has double edges on its sides:

In java active classes extend Java's Thread class and override its run method:

In the Master-Slave pattern one active object is designated the master (this might be the server or user interface). It is responsible for creating and launching active slave objects:

Here's some sample code:

Slave.java

Master.java

TestMaster.java

Master-Slave-Resource

Problem

The slaves in the Master-Slave pattern need to query and update a shared resource (such as a joint bank account):

If two slaves access the shared resource simultaneously, then data may be corrupted.

Solution

Every Java object can be locked and unlocked. Only one thread at a time can lock and subsequently unlock an object.

If a thread attempts to lock a locked object, it is blocked and placed in a queue. Only when the locking thread unlocks and object can the next thread in the queue lock the object.

Declaring a method "synchronized" means that before a thread calls the method, it must first lock the object. When the method terminates, the object is automatically unlocked. Thus, only one thread at a time can execute a synchronized method.

Resource.java

Slave.java

Master.java

TestMaster.java

 

(Try running this program with and without synchronizing the resource.)

References

Multi-Threading in Java