问题
Does any one know of any good java libraries/API packages that performs zero copy data transfers between two or more sockets? I know that Java's NIO API can perform zero copy data transfers from disk to socket and vice versa using java.nio.channels.FileChannel.transferTo and java.nio.channels.FileChannel.transferFrom methods respectively. However, there doesn't appear to be support for java socket to socket zero copy transfers. In addition any java libraries/API that can perform the system call splice (which can transfer data from a file descriptor to a pipe and vice versa) would be a plus, preferably on a linux platform.
Thank you for response.
In addition, I have read most of the previous blogs about zero copy as well as other informative sites such as http://www.ibm.com/developerworks/library/j-zerocopy/; However, it appears the above issue has not been addressed.
回答1:
I don't know much about SocketChannel, but I think ByteBuffer.allocateDirect()
is a good choice for you.
Just read socket A's data into ByteBuffer.allocateDirect()
and let socket B read from it, simple and easy.
Here's the differences:
1. Old Way
SocketA --> BufferA(Kernel Space) --> BufferB(User Space)
BufferB(User Space) --> BufferC(Kernel Space) --> SocketB
2. Zero Copy Way
SocketA --> DirectBuffer(Could be accessed from Kernel and User Space)
DirectBuffer --> SocketB
Note
IMHO, I don't think we can make it directly SocketA -> SocketB
, the os need to load data into physical memory before send them out.
========= EDIT =========
According to the article you referred, FileChannel's transferTo do it this way :
Use ByteBuffer.allocateDirect()
you don't need to switch context between Kernel and User space. The only buffer is mapped to physical memory while reading and sending use the same blocks.
来源:https://stackoverflow.com/questions/20897315/using-java-to-perform-zero-copy-data-transfers-between-two-or-more-sockets