Dienstag, 4. November 2008

message propagation in a network, classic client/server

There is an application, which consists of many nodes connected to one hub. When a node sends something, it does so by sending a message to the hub. The hub itself will propagate this message to all other nodes.

A node knows 2 queues, one for incoming and one for outgoing messages. An underlying library knows the same 2 queues. The node expects the library to send messages from the outgoing queue to the hub. And it expects the library to put messages from the hub into the incoming queue.

I like the fact, that the node does not have to interact with the library at all. It just starts the library within the runtime, passing those 2 queues and thats it.



// Bootstrap
Properties props = ...; // data where to connect to
Queue in = new MyQueue();
Queue out = new MyQueue();
ClusterNodeLib lib = new ClusterNodeLib(props,in,out);
App app = new App(lib);



--


The underlying library polls from the outgoing queue and writes the message on the socket. It also polls the socket for incoming messages to add them on the outgoing queue. And in a third way, the library ensures, that there is always a connection to the hub.



//Library Bootstrap
Runnable socketWriter = new Runnable() {
public void run() {
Object msg = out.peek();
try {
writeOnSocket(msg)
out.poll();
} catch (Throwable t) {
t.printStackTrace();
}
}
}

Runnable socketReader = new Runnable() {
public void run() {
try {
Object msg = readFromSocket();
in.add(msg);
} catch (Throwable t) {
t.printStackTrace();
}
}
}

Runnable keepSocketAlive = new Runnable() {
public void run() {
try {
if (isSocketBroken()) {
reconnect();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}



--


The used pattern in this example is a typical one. It is quite easy to create and understand. Java offers queues, which are thread-safe in a concurrent environment and for the socket status, you would need to use some thread-safe variables too. With keeping the runnables alive, for example with a ThreadPool, there is not much more left to do.

Keine Kommentare: