java.lang.String API suggestion : make String return read-only CharBuffer

Eugene Chung(정의근) euigeun_chung at tmax.co.kr
Thu Apr 4 19:40:03 PDT 2013


Hello, Java SE 8 EG.


I'm a member of TmaxSoft, which is making the JEUS web application server.
And the implementor of a Servlet container.

I am writing to you that I'd like to suggest a new method to
java.lang.String like below:

/**

 * Returns a read-only char buffer that shares this string's content.
 * @return a read-only char buffer
 */
public java.nio.CharBuffer getAsCharBuffer() {
     return CharBuffer.wrap(value).asReadOnlyBuffer();
}


Since Java EE Servlet 3.1, a Servlet container provides non-blocking I/O to
web applications. So, javax.servlet.ServletOutputStream#print(String
s) supports non-blocking
write.

Before writing 's' to a socket stream, we must convert it to a byte array.
We can use s.getBytes(charset), if 's' is small enough. But if 's' is
big enough, we cannot use getBytes() because it can cause
memory exhaustion or more seriously OutOfMemoryError. To avoid the
problem, we need a fixed-size char array and byte array for
intermediate conversion.

Here's the pseudo code to explain why String should return read-only
CharBuffer.
Let's call the name of char array 'cbuff' and the name of result byte array
'bbuff'.

for (toStringEnd) {
   s.getChars(b, e, cbuff, cbuff.length); // 1

   charsetEncoder.encode(CharBuffer.wrap(cbuff), ByteBuffer.wrap(bbuff),
false); // 2

   // write 'bbuff' to socket
}
>From above code, '1' and '2' are necessary operations but definitely
memory copy overhead. Copy overhead of '2' is unavoidable but we can
remove overhead of '1' if

String offers backing CharBuffer as I've suggested.


CharBuffer charBuffer = s.getAsCharBuffer();
for (charBuffer.hasRemaining()) {

   // NO OVERHEAD Of 1


    charsetEncoder.encode(charBuffer, ByteBuffer.wrap(bbuff), false); // 2


   // write 'bbuff' to socket
}


It doesn't harm immutability of String because CharBuffer returned from
it is read-only. (CharBuffer.asReadOnlyBuffer())

And I think this new method can help many applications to reduce memory copy
overhead of String.


Best regards,
Eugene Chung (Korean : 정의근)


More information about the jdk8-dev mailing list