StringBuffer Absorbs Concurrent Appends
Race the same append loop on a shared StringBuffer and StringBuilder: the synchronized buffer lands every char, the unsynchronized one prints its shortfall.
Code
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.IntSupplier;
public class SharedBufferRace {
// 只有两个方法的窄接口:append 语义由 StringBuffer/StringBuilder 提供
interface Chars {
void add(char c);
}
static final int THREADS = 4;
static final int APPENDS_PER_THREAD = 10_000;
// 同一段竞速代码,唯一变量是 append 的实现是否 synchronized
static int run(Chars sink, IntSupplier length) throws InterruptedException {
CountDownLatch ready = new CountDownLatch(THREADS);
CountDownLatch go = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(THREADS);
ExecutorService pool = Executors.newFixedThreadPool(THREADS);
for (int t = 0; t < THREADS; t++) {
pool.execute(() -> {
ready.countDown();
try {
go.await();
for (int i = 0; i < APPENDS_PER_THREAD; i++) {
sink.add('x');
}
done.countDown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
ready.await();
go.countDown();
done.await();
pool.shutdown();
return length.getAsInt();
}
public static void main(String[] args) throws InterruptedException {
int expected = THREADS * APPENDS_PER_THREAD;
StringBuffer safeBuffer = new StringBuffer();
int safe = run(safeBuffer::append, safeBuffer::length);
System.out.println("expected: " + expected);
System.out.println("StringBuffer: " + safe);
StringBuilder fastBuffer = new StringBuilder();
int racy = run(fastBuffer::append, fastBuffer::length);
System.out.println("StringBuilder: " + racy + " (missing " + (expected - racy) + ")");
}
}How the snippet works
StringBuffer Absorbs Concurrent Appends reduces to the classes SharedBufferRace and Chars.
for (int t = 0; t < THREADS; t++) is the loop that carries the per-item work.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
Expect labeled output — expected:, StringBuffer:, StringBuilder: — when the file runs.
Key statements worth quoting
ExecutorService pool = Executors.newFixedThreadPool(THREADS);
Thread.currentThread().interrupt();
return length.getAsInt();
Interactive Tools for This Topic
FAQ
- What does StringBuffer Absorbs Concurrent Appends print when run?
- Running the file directly is enough — expect labeled output lines such as `expected:`, `StringBuffer:`, `StringBuilder:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.