Search code examples
javamultithreadingconcurrencystringbuffer

Why StringBuffer#append throws StringIndexOutOfBoundsException


I have the code which tries to append 2 SttringBuffers:

logBuf.append(errStrBuf);

In logs I see following trace:

java.lang.StringIndexOutOfBoundsException: String index out of range: 90
    at java.lang.AbstractStringBuilder.getChars(AbstractStringBuilder.java:325)
    at java.lang.StringBuffer.getChars(StringBuffer.java:201)
    at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:404)
    at java.lang.StringBuffer.append(StringBuffer.java:253)

I cannot understand the cause of the issue.

Can you provide example with constants?

Can it be related with concurrency?

Can you propose solution?


Solution

  • Yes, it can have to do with concurrency. As per the doc:

    This method synchronizes on this (the destination) object but does not synchronize on the source (sb).

    So, if errStrBuf is changed in the process, it may yield this error. Synchronize on it yourself, as such:

    synchronize (errStrBuf) {
       logBuf.append(errStrBuf);
    }
    

    using the same synchronized-block wherever the errStrBuf is changed.