Java NIO Servlet to file

Is there a way (without buffering the entire Inputstream) to take the HttpServletRequest from the Java servlet and write it to a file using all the NIOs? Should I even try? Will it be faster reading from a regular java.io stream and writing to the java.nio channel, or do they really need to be pure NIO to see the advantage? Thanks.

EDIT:

So, I just did a quick and dirty test by reading a file from one disk and writing to another disk (so I actually test the code, not the disk).

Averages: InputStream -> OutputStream : 321 ms. FileChannel -> FileChannel : 3 ms. InputStream -> FileChannel : 600 ms. 

I really got worse performance when trying to use hybrid java.io -> java.nio. Nio-> nio was faster than A LOT, but I was stuck in a Servlet InputStream.

+7
java performance servlets nio
source share
4 answers

The main advantage of a clean NIO solution is that you can avoid copying data from the kernel to the user and back to the kernel space. When you use the transferTo() or transferFrom() operation, these overheads can be avoided, and the transfer between channels can be very fast (depending on the underlying implementation).

However, the servlet API does not allow you to access the Channel source; by the time your servlet sees the data, it is in user space. Therefore, I did not expect performance improvements from recording to Channel .

+6
source share

HttpServletRequest gives you the usual "pull" input stream - I don’t see how NIO will help here.

+1
source share

you cannot seriously compare performance with tests that are reduced to milliseconds.

discs will not spin faster due to the choice of API. what happened in FileChannel-> FileChannel, it is likely that the call was returned before the records were actually committed to disk.

nio can save some CPU / memory usage. but not much in your situation. to save files downloaded by users, as a rule, in multipart / form-data format, and the server must read byte bytes for parsing input and extracting the contents of the file, it cannot just dump the raw stream to the file directly.

+1
source share

I think you are not worried. The average network speed (~ 1 MB / s) cannot catch up with the average speed of the hard drive (~ 100 MB / s), of course (even with the most optimistic average). File channels will not give you any benefits. The "legacy" of java.io more than enough.

0
source share

All Articles