Search code examples
javaarraysserializationdata-exchange

Fastest way to exchange an array of double between two java programs


I need two separate java programs, running in separate JVMs to exchange numeric data as fast as possible through either a file stream (linux pipe) or over a network connection.

Every message is a double[] where the length of the array can vary from message to message. I would be interested what the fastest way to do this is, especially in a situation where both JVMs run on the same machine or the same hardware.

In a C-like language, this could be done by just aliasing the array to a byte buffer and transferring the byte buffer as is (plus a small header that will tell the recipient about the size of the array to create to take up the buffer). Is something similar possible with Java?


Solution

  • Over a socket connection, use an ObjectOutputStream to write the object directly to the stream, and use an ObjectInputStream to deserialize at the other end.

    Put simply, to send:

    OutputStream out; // of socket
    double[] array;
    
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeObject(array);
    

    To receive:

    InputStream in; // of socket
    ObjectInputStream ois = new ObjectInputStream(in);
    
    double[] array = (double[])ois.readObject();
    

    This uses java's built-in serialization library, which is as fast as possible. All primitives and arrays of primitives are serializable this way (as is anything that implements @Serializable).