-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Zero-copy NIO channel read & write #1172
Comments
I've been hoping okio would have some socket like interface for a while. Would make things like OkHttp/Wire working multiplatform possible. Possible implementations, 1) Socket, 2) TLS Socket, ... Could you gain anything by expressing this problem with an Okio socket like interface? |
Yep, I think that’s appropriate. Particularly for Kotlin/Native, where we don’t yet have a multiplatform socket. |
Hi, Java uses a direct ByteBuffer pool to avoid allocating and zero-fill a new direct ByteBuffer every time, like Okio does for segments, but it is always copying from heap to native memory on each operation. Wrapping a See static int write(FileDescriptor fd, ByteBuffer src, long position,
boolean directIO, boolean async, int alignment,
NativeDispatcher nd) throws IOException {
if (src instanceof DirectBuffer) {
return writeFromNativeBuffer(fd, src, position, directIO, async, alignment, nd);
}
// Substitute a native buffer
ByteBuffer bb = Util.getTemporaryDirectBuffer(rem);
try {
bb.put(src);
// ... And private int tryWrite(FileDescriptor fd, byte[] b, int off, int len) throws IOException {
ByteBuffer src = Util.getTemporaryDirectBuffer(len);
try {
src.put(b, off, len);
return nd.write(fd, ((DirectBuffer)src).address(), len);
} finally {
Util.offerFirstTemporaryDirectBuffer(src);
}
} |
I’m experimenting using
okio.Buffer
withSocketChannel
.One challenge is
SocketChannel
doesn’t offer APIs that fit Okio:I can accomplish my goals by creating a temporary
ByteBuffer
, then copying its results into an Okio Buffer with these existing functions from theByteChannel
supertype:But copying an extra time sucks, let’s not do that!
A better alternative is @bnorm’s awesome ByteChannelSink sample, which uses
ByteBuffer.wrap()
.I’d like to get something like that into Okio, as extension functions on the appropriate NIO channel types:
Cache ByteBuffer instances?
Should we cache result of
ByteBuffer.wrap()
as a field onSegment
? It has the potential to be a frequent allocation, though it’s also one that the VM should be able to escape-analysis away. Looking at JOL, we could add aByteBuffer
field without immediately harming the size ofSegment
.For now I’d like to start by not caching, especially since doing so would require
Segment
to be split into JVM and non-JVM declarations.The text was updated successfully, but these errors were encountered: