Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4375495

Race condition between deleteCharAt() and substring() in StringBuffer

XMLWordPrintable

    • beta
    • generic
    • generic



      Name: tb29552 Date: 10/02/2000


      /*
      C:\>java -version
      java version "1.3.0"
      Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0-C)
      Java HotSpot(TM) Client VM (build 1.3.0-C, mixed mode)

      If a thread invokes the substring(int) method on a shared StringBuffer, and
      another thread concurrently invokes delete(int, int) or deleteCharAt(int) on the
      same StringBuffer, substring may throw a StringOutOfBoundsException. This
      happens because substring is not synchronized and may use an old size but a new
      buffer.

      The following example eventually throws an exception:

      % java -showversion SbTest
      java version "1.3.0"
      Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0)
      Java HotSpot(TM) Client VM (build 1.3.0, mixed mode)

      java.lang.StringIndexOutOfBoundsException: String index out of range: 26
              at java.lang.StringBuffer.substring(StringBuffer.java:702)
              at java.lang.StringBuffer.substring(StringBuffer.java:679)
              at SbTest$2.run(SbTest.java:42)
      */

      class SbTest {
          static StringBuffer sb =
              new StringBuffer("abcdefghijklmnopqrstuvwxyz");

          public static void main(String[] args) {
              Thread t1 = new Thread() {
                  public void run() {
                      while (true) {
                          sb.deleteCharAt(0);
                          sb.insert(0, 'a');
                      }
                  }
              };
              Thread t2 = new Thread() {
                  public void run() {
                      while (true) {
                          sb.substring(0);
                      }
                  }
              };
              t1.start();
              t2.start();
          }
      }

      (Review ID: 110249)
      ======================================================================

            mmcclosksunw Michael Mccloskey (Inactive)
            tbell Tim Bell
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: