Both the StringBuffer and StringBuilder classes are used to create mutable strings. But StringBuffer are synchronized, which means that only one task is allowed to execute the methods.
Consider the following program which appends a “-” mark to a StringBuilder object by 100 threads.
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class MutableStringDemo{
static StringBuilder stringBuilder = new StringBuilder();
public static void main(String[] args) throws InterruptedException {
Runnable runMethod = ()->{
stringBuilder.append("-");
};
stringBuilder.append("Hello");
ThreadPoolExecutor thread = (ThreadPoolExecutor) Executors.newCachedThreadPool();
for(int i = 100; i>0; i--) {
thread.execute(runMethod);
}
System.out.println(stringBuilder);
}
}
OUTPUT>>
Hello----------------------------
Here as you see the output, it does not append 100 “-” marks to the object. This is why because the stringBuilder object is accessed by 100 threads concurrently which cause to corrupt the expected result. This is the main problem with the StringBuilder class. But if you use the StringBuffer class this problem will not arise.
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class MutableStringDemo{
static StringBuffer stringBuffer = new StringBuffer();
public static void main(String[] args) throws InterruptedException {
Runnable runMethod = ()->{
stringBuffer.append("-");
};
stringBuffer.append("Hello");
ThreadPoolExecutor thread = (ThreadPoolExecutor) Executors.newCachedThreadPool();
for(int i = 100; i>0; i--) {
thread.execute(runMethod);
}
System.out.println(stringBuffer);
}
}
OUTPUT>>
Hello------------------------------------------------------------------------------------------------
here you will see 100 “-” marks.