2

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?

jpp1
  • 2,019
  • 3
  • 22
  • 43

1 Answers1

2

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).

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • It occurred to me two minutes after posting the question that using Java's Object*Stream is probably among the fastest but also the most portable way to do this and it does not need any library! Thanks! – jpp1 May 19 '16 at 09:32