0

Which would be the fastest way to copy a file over a socket? I have tried several ways but I am not convinced I found the fastest way concerning transfer and CPU usage. (Best result: 175mBit/s (SSD/GBit Network))

Server:

ByteBuffer bb = ByteBuffer.allocate(packet_size);
DataOutputStream data_out = new DataOutputStream(socket.getOutputStream());

while(working){

    int count =0;
    int packet_size = in.readInt();
    long pos = in.readLong();
    if(filechannel.position()!=requested_pos){
        filechannel.position(requested_pos);
    }
    bb.limit(packet_size);
    bb.position(0);
    if((count=filechannel.read(bb))>0){  //FileInputStream.getChannel()
        data_out.writeInt(count);
        data_out.write(bb.array(),0,count);
    }else{
     working=false;
    }
}

Client:

for(long i=0;i<=steps;i++){

    data_out.writeInt(packet_size);     //requested packet size
    data_out.writeLong(i*packet_size);  //requested file position

    count=in.readInt();
    bb.clear();
    bb.limit(count);

    lastRead=0;
    while(lastRead<count){
        lastRead+=in.read(bytes,lastRead,count-lastRead);  
    }
    bb.put(bytes,0,count);
    bb.position(0);
    filechannel.write(bb); // filechannel over RandomAccessFile
 }

any suggestions?

1
  • 2
    You can compress blocks and decompress at other end. For example give a try for snappy java
    – qwr
    Nov 22, 2016 at 14:11

2 Answers 2

4

You are looking at only half the issue. The code used to send/receive is only one factor. No matter how hard you optimize it, if you set up your socket with unsuitable parameters, performance takes a big hit.

For large data transfers, ensure the sockets have reasonably large buffers. I'd choose at least 64kb, possibly larger. Send and receive buffers can be set up independently, for the sender you want a large(r) send buffer and for the receiver a large(r) receive buffer.

    socket.setReceiveBufferSize(int);
    socket.setSendBufferSize(int);
    socket.setTcpNoDelay(false);

Set TCP NO DELAY to OFF, unless you know what you're doing and after confirming you really absolutely need it. It will never improve throughput, on the contrary it may sacrifice throughput in favor of reduced latency.

The next thing is to tailor your sender code to do its best to keep that buffer full at all times. For maximum speed reading from the file and writing to the socket should be separated into two independent threads, communicating to each other using some kind of queue. Chunks in the queue should be reasonably large (at least a few kb).

Likewise the receiving code should do its best to keep the receive buffer as empty as possible. Again, for maximum speed this requires two threads, one reading the socket and another processing the data. Queue in between like the sender.

The job of the queues is to decouple stalls in reading data from file/writing to file from the actual network transfer, and vice versa.

The above is the generic pattern how you get maximum throughput, regardless of transmission channels. The slower channel will be kept completely saturated, be it file reading/writing or network transfer.

Buffer sizes can be tweaked to squeeze out the last few percent of possible performance (I'd start with 64kb for the socket and 8kb chunks in the queue with a maximum queue size of 1mb, this should deliver performance reasonably close to the maximum possible).

Another limiting factor you may run into is the TCP transfer window scaling (especially over a high bandwidth, high latency connection). Aside from ensuring the receiver empties the receive buffer as fast as possible there isn't anything you can do from the java side. Tweaking options exists on the OS level.

2
  • Good answer. Presumably the buffer doesn't need to be "full at all times" - it just needs to be kept topped up such that there's never less than a packet in there.
    – slim
    Nov 22, 2016 at 17:23
  • @slim Yes, thats exactly what I was trying to convey.
    – Durandal
    Nov 22, 2016 at 17:29
1

You want to use the NIO.

    import java.nio.ByteBuffer;
    import java.nio.channels.Channels;
    import java.nio.channels.ReadableByteChannel;
    import java.nio.channels.WritableByteChannel;


public class FileServlet extends HttpServlet {

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            try(final InputStream is  = new BufferedInputStream((InputStream) <YOUR INPUT STREAM TO A FILE HERE>);
                final OutputStream os = new BufferedOutputStream(response.getOutputStream()); ) {

                fastCopy(is, os);
            }

}

 public static void fastCopy(final InputStream src, final OutputStream dest) throws IOException {
    fastCopy(Channels.newChannel(src), Channels.newChannel(dest));
}



    public static void fastCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

        while(src.read(buffer) != -1) {
            buffer.flip();
            dest.write(buffer);
            buffer.compact();
        }

        buffer.flip();

        while(buffer.hasRemaining()) {
            dest.write(buffer);
        }
    }    
}

}
2
  • 1
    It's a myth that Java NIO is faster than Java IO. Nov 22, 2016 at 14:54
  • @fireandfuel Have you got some sources for that?
    – mal
    Oct 30, 2018 at 9:34

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.