Course Content
Keywords
Operators
Loops
String
Array
Object Oriented Principle
Memory Management
Collection Framework
Exception Handling
Reflection API
Multi Threading
File Handling
Java Version wise Questions
Java Scenario Based Interview Questions
About Lesson
Scenario: You have a StringBuilder being used by multiple threads to append values. What problems could occur, and how would you handle them in a multithreaded environment?

Answer:

StringBuilder is not thread-safe, which means that if multiple threads attempt to append to the same StringBuilder instance concurrently, it can result in data corruption or inconsistent results.

To handle this in a multithreaded environment, you can use StringBuffer (which is thread-safe) or synchronize the StringBuilder operations.

 

  • Using StringBuffer: Since StringBuffer is thread-safe, it can handle concurrent appends safely.

 


class ThreadSafeStringBuilder {
    private StringBuffer sb = new StringBuffer();

    public void appendString(String str) {
        sb.append(str);  // Thread-safe append operation
    }

    public String getString() {
        return sb.toString();
    }
}

 

 

  • Synchronizing StringBuilder: If you prefer to use StringBuilder for performance reasons, you can synchronize its usage:

 


class ThreadSafeStringBuilder {
    private StringBuilder sb = new StringBuilder();

    public synchronized void appendString(String str) {
        sb.append(str);  // Synchronized append operation
    }

    public synchronized String getString() {
        return sb.toString();
    }
}

By using StringBuffer or synchronization, you ensure that the StringBuilder or StringBuffer is accessed by only one thread at a time, preventing concurrent modification issues.