Oliver Spryn
Oliver Spryn

Reputation: 17368

Java Multicast Receive Data and Parallel Processing

I am writing a class in Java to simplify the process of connecting to, joining, sending, and receiving data from a multicast group. Please have a look at the sample below before I describe my question, just so you have an idea of what I am doing.

Here is a very basic code sample of what I am doing. Note that it does not at all resemble my actual code, with the exception catching, import statements, etc... it simply shows the basic flow of my class in how it leverages Java's multicasting abilities:

//Connect to the multicast host, and join the group
  MulticastSocket msConn = new MulticastSocket(5540);
  InetAddress netAddr = InetAddress.getByName("239.255.255.255");
  msConn.joinGroup(netAddr);

//Preapre a datagram packet in which to place recieved data
  byte buf[] = new byte[1024];
  DatagramPacket pack = new DatagramPacket(buf, buf.length);

//Code halts here until data is recieved
  msConn.recieve(pack);

Note that, on the receive() method, the code halts until the multicaster class receives a data packet. I would to be able to have Java continuously listen for new data, while also simultaneously executing this code:

int i = 0;

while(true) {
  System.out.print(i);
  i++;
}

Can these processes be done in parallel, and, if so, could you please provide an example of how to do this? If not, is there another work around?

Upvotes: 1

Views: 1130

Answers (1)

Mac
Mac

Reputation: 14791

If you want your program to be doing things simultaneously, you'll want to use threads.1

The easiest way (without going into things like anonymous classes, etc) is probably to split one or the other of your processes into a separate class that implements Runnable. For example, make a Counter class as follows:

public class Counter implements Runnable {
    public void run ( ) {
        int i = 0;
        while(true) {
            System.out.print(i);
            i++;
        }
    }
}

Then, just before your other code, you would create a new Thread as follows:

Counter counter = new Counter( );
Thread thread = new Thread(counter);
thread.start( );
...
// The rest of your code goes here...

This extra thread will execute in parallel with the original thread, which has now moved onto handling your sockets code. You could of course start a new thread for that too if you wanted, but it is a little redundant since you already have two threads (your new one and the original).

This is really just scratching the surface of threading. There's far more to it than I can really give in just this answer, so I strongly suggest reading through the linked docs, reading through the thread article on Wikipedia, and finding other info to get a better idea of how this stuff works.


1: If your threads run on the same processor they won't really be running simultaneously, they'll just seem to be doing so.

Upvotes: 3

Related Questions