I just copied a working example of data transfer from this forum and used it with little change in my program, but I can't see what's the problem with its speed. I tested the main example and it transfers some 1MB in less than 30ms. Both read and write speed is very good. But when I use it in my case the same amount of data is not transfered in less than 400ms! The writing remains effecient, but reading is somehow problematic.
Here the data is written. For now, I'm not trying to speed up the first part, i.e. the serialization of the object. My question is about the second part.
private static void writeObject(OutputStream out, Object obj) throws IOException {
long t1 = System.currentTimeMillis();
ByteArrayOutputStream bArr = new ByteArrayOutputStream();
ObjectOutputStream ojs = new ObjectOutputStream(bArr);
ojs.writeObject(obj);
ojs.close();
long t2 = System.currentTimeMillis();
byte[] arr = bArr.toByteArray();
int len = arr.length;
for (int i = 0; i < arr.length; i += BUFFER_SIZE)
out.write(arr, i, Math.min(len - i, BUFFER_SIZE));
out.close();
long t3 = System.currentTimeMillis();
System.out.println(t3 - t2);
}
Well, this is not that bad! t3 - t2
prints some 30ms.
The problem is here, in readObject()
, and not in its second part, where the object is deserialized, at least not for now, but the problem is in the first part, where t2 - t1
turns out to be more than 400ms, as I mentioned.
private static Object readObject(InputStream in) throws IOException, ClassNotFoundException {
long t1 = System.currentTimeMillis();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte[] buff = new byte[BUFFER_SIZE];
int read;
while ((read = in.read(buff)) != -1) {
bao.write(buff, 0, read);
}
in.close();
long t2 = System.currentTimeMillis();
ByteArrayInputStream bArr = new ByteArrayInputStream(bao.toByteArray());
Object o = new ObjectInputStream(new BufferedInputStream(bArr)).readObject();
long t3 = System.currentTimeMillis();
System.out.println(t2 - t1);
return o;
}
And here is the main()
:
final static int BUFFER_SIZE = 64 * 1024;
public static void main(String[] args) throws Exception {
final String largeFile1 = "store.aad";
final Table t = (Table) new ObjectInputStream(new FileInputStream(largeFile1)).readObject();
new Thread(new Runnable() {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(12345);
Socket clientSocket = serverSocket.accept();
readObject(clientSocket.getInputStream());
} catch (Exception e) {
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
Socket socket = new Socket("localhost", 12345);
OutputStream socketOutputStream = socket.getOutputStream();
writeObject(socketOutputStream, t);
} catch (Exception e) {
}
}
}).start();
}
Where am I going wrong?!