0
public class Log {

    private static StringBuilder log = new StringBuilder();

    private static StringBuilder getLog() {

        return log;

    }


    public static void addToLog(String id, String name, String field, String operator, String value, String bValue) {

        Calendar calendar = Calendar.getInstance();
        String currentTime = formatter.format(calendar.getTime());
        getLog().append(currentTime); // line 114

    }

}

Stack trace:

[java] Exception in thread "Thread-5" java.lang.ArrayIndexOutOfBoundsException 
[java]     at java.lang.String.getChars(String.java:863) 
[java]     at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:416) 
[java]     at java.lang.StringBuilder.append(StringBuilder.java:132) 
[java]     at com.retroficiency.system.Log.addToMatchingLog(Log.java:114)

This method usually works fine, but we encountered this random error, which I can't figure out why. There is a seperate method that flushes the log to a file and clears it with:

getLog().delete(0, getMatchingLog().length());

I do not suppose it is a Java bug? Is it getting too long? Thanks for any help!

jn1kk
  • 5,012
  • 2
  • 45
  • 72

2 Answers2

11

StringBuilder is not thread-safe. You should be using StringBuffer in this case.

You can find more info in this other SO thread:

Difference between StringBuilder and StringBuffer

Community
  • 1
  • 1
mjuarez
  • 16,372
  • 11
  • 56
  • 73
3

There is no reason why this would happen, unless you access this method from different threads: StringBuilder is not thread safe. You could use a StringBuffer, which is thread safe or add some form of synchronization.

Javadoc:

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

assylias
  • 321,522
  • 82
  • 660
  • 783