Java Reference
In-Depth Information
Router
The Router can be useful at various places in the example application. In almost every situation where there is
more than one interested party in any event, you can use the Router. The Router is essentially an implementation
of a listener structure; you will see some similarities.
The code for the
Message
class is shown here. It is a container for the source (an
InputChannel
) and the actual
message—in this case, some
String
.
Example A.245
Message.java
1. import java.io.Serializable;
2. public class Message implements Serializable{
3. private InputChannel source;
4. private String message;
5.
6. public Message(InputChannel source, String message){
7. this.source = source;
8. this.message = message;
9. }
10.
11. public InputChannel getSource(){ return source; }
12. public String getMessage(){ return message; }
13. }
Example A.246
InputChannel.java
1. import java.io.Serializable;
2. public interface InputChannel extends Serializable{}
The
OutputChannel
is the interface that defines the method for sending the message to the target. Since the
OutputChannel
can be used to communicate between machines, it is defined as a remote interface.
Example A.247
OutputChannel.java
1. import java.rmi.Remote;
2. import java.rmi.RemoteException;
3. public interface OutputChannel extends Remote{
4. public void sendMessage(Message message) throws RemoteException;
5. }
The
Router
uses a hash map to store links between the specific
InputChannel
and various
OutputChannels
.
When it receives a message, it looks up the destinations in its map.
It loops through the collection and sends the message to each of the destinations. In this example, the
Router
creates a worker thread (see “
Worker Thread
” on page 517) to send a message to each of its
OutputChannel
objects.
Thread pools are often used to improve performance in applications such as these.
Example A.248
Router.java
1. import java.rmi.Naming;
2. import java.rmi.RemoteException;
3. import java.rmi.server.UnicastRemoteObject;
4. import java.util.HashMap;
5. public class Router implements OutputChannel{
6. private static final String ROUTER_SERVICE_NAME = "router";
7. private HashMap links = new HashMap();
8.
9. public Router(){
10. try {
11. UnicastRemoteObject.exportObject(this);
12. Naming.rebind(ROUTER_SERVICE_NAME, this);
13. }
14. catch (Exception exc){
15. System.err.println("Error using RMI to register the Router " + exc);
16. }
17. }
18.
19. public synchronized void sendMessage(Message message) {
20. Object key = message.getSource();
21. OutputChannel[] destinations = (OutputChannel[])links.get(key);