P R
P R

Reputation: 1301

Race condition during serialization

My application has a master and many slaves which respond to the master's call-over sockets and send the statistics over in an object. Right now, I'm testing the code with one master and two slaves. Code works fine with 1 slave but with 2 slaves, the objects received at the master's end get populated twice i.e Two copies of the same object.

Maser's code: The master receives periodically from slaves and hence exceuting using a timer:

public void run() {

    try {
        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        DatagramSocket dSock = new DatagramSocket(4445);
        dSock.receive(packet);
        int byteCount = packet.getLength();
        ByteArrayInputStream byteStream = new ByteArrayInputStream(recvBuf);
        ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(byteStream));
         //receiving the object pm of class PM
        pm1=(PM)is.readObject();
        }
 }

and the slave's code:

 {
 InetAddress address = InetAddress.getByName("10.129.54.254");
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream(15000);
            os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
            os.flush();
            //sending the object pm of class PM
            os.writeObject((PM)pm);
            os.flush();
            byte[] sendBuf = byteStream.toByteArray();
            DatagramPacket packet = new DatagramPacket(sendBuf, sendBuf.length, address, 4445);
            int byteCount = packet.getLength();
            DatagramSocket dSock = new DatagramSocket();
            dSock.send(packet);
            os.close();
            dSock.close();
            }
      }

Doubt: 1. Should I store the objects from the two slaves in an array? If so, how do I differentiate between the two received object over the socket so that the same object isn't stored twice? Assuming that the object sent over has a unique attribute such as id. ie

class PM{
int uniqueid;
}
  1. I'm trying to write the entire code and hence don't want to use Jini or other APIs. Thanks!

Upvotes: 2

Views: 540

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

When you receive

     //receiving the object pm of class PM
    pm1=(PM)is.readObject();

Don't just store it in a field as the next object from the second slave will also be placed in that fields.

Instead you should use a local variable, read the contents of the object and act on it. Or if you want another thread to process it, add a task to a single threaded ExecutorService to process the objects.

Upvotes: 3

Related Questions