StringBuffer has the same append/insert/reverse API as StringBuilder, but every method is synchronized, so two threads appending to the same buffer never lose a character the way an unsynchronized StringBuilder could. That safety costs a lock acquisition on every single call.
StringBuffer buffer = new StringBuffer();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) buffer.append('x');
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final length, no lost appends: " + buffer.length());
Final length, no lost appends: 2000
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27