StringBuffer.toString() is not thread safe.

mbjb14 at dial.pipex.com mbjb14 at dial.pipex.com
Fri Sep 25 15:26:02 PDT 1998


Hi,

StringBuffer.toString() does not look thread safe.

Also, perhaps this method should just call the String(StringBuffer) 
constructor directly as this would have the added benifit of cutting
out the creation of one of the character arrays.
However this is not thread safe either.

A suggested fix follows.

Steve.


--- String.java.orig	Fri Sep 25 23:03:41 1998
+++ String.java	Fri Sep 25 23:10:35 1998
@@ -39,10 +39,12 @@
 
 public String (StringBuffer sb)
 	{
-	count = sb.length();
-	value = new char[count];
-	if (count > 0)
-		sb.getChars(0, count, value, 0);
+	synchronized (sb) {
+		count = sb.length();
+		value = new char[count];
+		if (count > 0)
+			sb.getChars(0, count, value, 0);
+	}
 }
 
 public String( byte[] bytes)
--- StringBuffer.java.orig	Fri Sep 25 23:03:50 1998
+++ StringBuffer.java	Fri Sep 25 23:04:13 1998
@@ -240,10 +240,6 @@
 
 public String toString()
 	{
-	char buf[] = new char[used];
-	if (used > 0) {
-		getChars(0, used, buf, 0);
-	}
-	return new String(buf);
+	return new String(this);
 }
 }



More information about the kaffe mailing list