cross thread communication java cross thread communication java multithreading multithreading

cross thread communication java


I was originally going to keep an array list of the nodes, but then I realized all the nodes needed to be there own thread.

You can keep an array of threads, it would still maintain a thread-per-node with the same logic structure.

how do I pass information back in forward between threads in Java.

If threads reside in the same process then definitely sockets are an overkill. I would use one or several ConcurrentLinkedQueue instances to push/pop messages.

One or several really depends on the kind of communication that you are implementing. Maybe one ConcurrentLinkedQueue per node, so nodes push messages to queues and every node knows where from to pop the message.

Few hints for implementation

Wrap up all the logic to en-route messages in a class - let's call this class VirtualNetwork. VirtualNetwork deals with all the instances of ConcurrentLinkedQueue and offers an API of methods to all threads for sending/receiving messages. Make one instance of the class VirtualNetwork accessible to all nodes - by passing a reference to it on the Thread constructor.

This is an sketch of how your class NodeThread would be. Notice that the classes VirtualNetwork and Message are classes that you have to implement your self.

class NodeThread extends Thread {    private int nodeId;    private VirtualNetwork network;    public NodeThread(int nodeId,VirtualNetwork network) {        this.network = network;        this.nodeId = nodeId;    }    public void run() {        /* when you have to send */        int nodeReceptor = this.nodeId -1; /* neighbor in the array of threads */        Message m = new Message(this.nodeId,nodeReceptor);        m.setContent(10);        network.send(m);        /* when you have to receive */        Message m = network.receive(this.nodeId);        /* it's your decision to implement this in a blocking way or not */    }} 


An easy (if not optimal) way to start is to create a BlockingQueue for each pair of threads that need to pass values in one direction (if it's bidirectional you need twice as many.)


You could definitely use Sockets. There are a couple of tutorials/descriptions here and here. Your description of the project suggests a client/server setup would work well since you have a central "master node". The master will be the server and the other threads will be able to connect to the master/server to receive their updates.