Observable approach feedback requested

J

Jeffrey Drew

I want to enhance my code with the Observable/Observer functionality in
Java, but haven't found much writing on it. I have a simple example running
and would appreciate feedback.

PROBLEM:
multiple computers send data to a Java server I've written. The server
process creates a new thread for each computer in typical Java fashion. I
want the server threads to update observer threads. Observer threads
register for data from one or more server threads. How do the Observer
threads reference the server threads?

I have the following solution, but putting threads in a HashMap seems like a
hack. I've only included here the relevant code to save reviewers time.
The full example does run.

MY SOLUTION:
// in one file, there's a parent server that starts the other classes
public class parentServer {
// data structure to hold thread references
HashMap threadHashMap = new HashMap();

parentServer() {
observableServer ot = new observableServer();
ot.setName("A");
Thread t = new Thread( ot );
t.start();
observerServer os = new observerServer();
}
}

// in another file, there's a server class
public class observableServer {
producerSocket = socket.accept();
serverThread st = new serverThread( probeSocket );
Thread t = new Thread( st );
t.start();

// I use the ip address of the producing computer as a key in a
HashMap
InetAddress ia = producerSocket.getInetAddress();
ipKey = ia.getHostAddress();

// so I could create a HashMap of references to threads by
producing computer
parentServer.threadHashMap.put( ipKey , st );

class serverThread extends Observable implements runnable {
// lots of reading and processing code in the run method
}
}

// in a separate file and class, I have the Observers. I'm considering...
class observerServer implements Observer {
public void observerServer() {
// look up the producing thread that the Observer will
listen for
observableServer.serverThread t1 =
(observableServer.serverThread) threadHashMap.get( ipKey );

// register to be notified by that producing server thread
t1.addObserver( this );
}
}

Is this a good approach? It seems like a poor way to reference a thread,
but I haven't found another. Is there a more elegant, optimal approach?

Thanks

Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top