Search code examples
javanio

FileChannel.transferTo() keeps transferring 0 bytes?


I asked this question yesterday, and I was convinced that a single-threaded file server will fit my need. Yes, with a single thread, the file server works pretty well(for only small files), it can handle about 300 requests per second, now the problem is that the write(I use FileChannel.transferTo()) part of the server will block for quite a while for serving large files, which keeps other connections from being connected.

I noticed that FileChannel.transferTo() sometimes transfers 0 bytes when transferring large files(around 800KB). It fails with: java.io.IOException: Try again. This was on Android.

Because I put FileChannel.transferTo() in a loop, I can get the situation where FileChannel.transferTo() runs thousands of times to ultimately transfer the entire file.

My question is what causes FileChannel.transferTo() fail to transfer the bytes requested? How do I tackle this problem and make my file server more responsively for handling large files?


Solution

  • The method can't possibly return zero and throw an exception at the same time, but I suggest that when you get 'try again' you should reduce the transfer count. I would keep halving it until the condition goes away. You have to call transferTo() in a loop anyway, so it doesn't really affect your code too much.