Java Reference
In-Depth Information
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 231) to send a message to each of its OutputChannel
objects. Thread pools are often used to improve performance in applications such as these.
Example 4.28 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);
22. new RouterWorkThread(message, destinations);
23. }
24.
25. public void addRoute(InputChannel source, OutputChannel[] destinations) {
26. links.put(source, destinations);
27. }
28.
29. private class RouterWorkThread implements Runnable{
30. private OutputChannel [] destinations;
31. private Message message;
32. private Thread runner;
33.
34. private RouterWorkThread(Message newMessage, OutputChannel[] newDestinations){
35. message = newMessage;
36. destinations = newDestinations;
37. runner = new Thread(this);
38. runner.start();
39. }
40.
41. public void run() {
42. for (int i = 0; i < destinations.length; i++){
43. try{
44. destinations[i].sendMessage(message);
45. }
46. catch(RemoteException exc){
47. System.err.println("Unable to send message to " + destinations[i]);
48. }
49. }
50. }
51. }
52. }
When using the Router pattern, be careful about the size of message to be delivered. Generally, the message
should be as small as possible. It is easy to be fooled by some Java objects, though. An object might have
references to other objects, which refer to other objects, and so on—and what seemed like a small object might
turn out to be very large indeed. For instance, sending a java.awt.Button is not a good idea, because the whole
GUI will be serialized and sent.
It's a lot like buying your child a toy in a store. The purchase of a single Outlaw Robot Laser Geek might not
seem expensive at first, but by the time you get all the accessories (extra pocket protector, laser-spitting
hornrimmed glasses), you might wonder if it would just be cheaper to buy him or her a sweater.
Search WWH ::




Custom Search