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

Eugene Chung(정의근) euigeun_chung at tmax.co.kr
Thu Mar 21 02:32:08 PDT 2013


Hello, Java SE 8 EG.


I'm Eugene from TmaxSoft, which is making a WAS.
And I'm currently managing the 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 error.
To avoid the problem, we need a fixed-size char 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()) {

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

   // write 'bbuff' to socket
}

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


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

So please consider about this.


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


More information about the java-se-8-spec-comments mailing list