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

Martin Buchholz martinrb at google.com
Wed Apr 10 18:04:29 PDT 2013


It's a reasonable suggestion, although the natural signature is

public CharBuffer asReadOnlyBuffer()

but where do you stop?  What about

public List<Character> asReadOnlyList()


On Thu, Apr 4, 2013 at 7:40 PM, Eugene Chung(정의근)
<euigeun_chung at tmax.co.kr>wrote:

> 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