Backend Development 10 min read

Understanding Thread Safety in Java: StringBuilder, StringBuffer, and Servlets

This article explains the thread‑safety differences between StringBuilder and StringBuffer, demonstrates the problems of using mutable shared objects in multithreaded Java code, presents three solutions, and discusses why Servlets are not thread‑safe by default, highlighting visibility and ordering concepts.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Understanding Thread Safety in Java: StringBuilder, StringBuffer, and Servlets

When reviewing the JDK API, you will notice that some classes are marked as thread‑safe or not thread‑safe; for example, the documentation for StringBuilder states that its instances are unsafe for use by multiple threads and recommends StringBuffer when synchronization is required.

StringBuffer is described as a thread‑safe mutable character sequence that can be safely used by multiple threads because its methods are synchronized, making all operations appear to occur in a serial order consistent with each thread’s method calls.

StringBuilder provides a similar API without synchronization, designed for single‑threaded use and generally faster than StringBuffer; using it across threads is unsafe, so StringBuffer should be used instead.

From the JDK description, the typical usage guidelines are:

Use String for small amounts of data.

Use StringBuilder for large data manipulation in a single thread.

Use StringBuffer for large data manipulation in multiple threads.

To illustrate the problem, a deliberately non‑thread‑safe class Count is created, and multiple threads increment its num field concurrently.

public class Count {
    private int num;
    public int getNum() { return num; }
    public void increment(int i) { num = num + i; }
}

The test spawns ten threads, each performing 1,000 increments, and prints the result. The output varies (e.g., Thread-0-1660 , Thread-9-9579 ) instead of the expected 1000 for each thread, demonstrating race conditions.

Three solutions are presented:

Move the counting logic inside the Count class using a local variable, eliminating shared state. public class Count { public void count() { int number = 0; for (int i = 0; i < 1000; i++) { number += 1; } System.out.println(Thread.currentThread().getName() + "-" + number); } }

Instantiate the Count object inside the run method so each thread works with its own local instance. public class ThreadTest { public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { Count count = new Count(); for (int i = 0; i < 1000; i++) { count.increment(1); } System.out.println(Thread.currentThread().getName() + "-" + count.getNum()); try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } }; for (int i = 0; i < 10; i++) { new Thread(runnable).start(); } } }

Avoid sharing mutable objects across threads altogether (not recommended).

Both of the first two approaches produce the correct output where each thread prints 1000 .

The article then explains Java’s two thread‑related properties: visibility and ordering. Visibility ensures that changes made by one thread to shared variables become visible to other threads, while ordering guarantees a deterministic execution sequence to avoid anomalies such as the classic bank‑account example.

Finally, the article discusses servlet thread safety. A servlet instance is a singleton in the container (e.g., Tomcat), so concurrent HTTP requests invoke the same object's service() method. If the servlet holds mutable instance or static fields, race conditions can occur. Stateless servlets—those without mutable fields—are inherently thread‑safe, which is why many service and DAO classes are designed to be stateless.

Javabackend developmentConcurrencyThread SafetyServletStringBuilderStringBuffer
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.