Sobes.tech
Junior

В чем различия между StringBuilder и StringBuffer в Java?

sobes.tech AI

Answer from AI

The main difference is that StringBuffer is thread-safe, while StringBuilder is not.

  • StringBuffer: All its methods are synchronized (synchronized). This ensures safety when working from multiple threads simultaneously, guaranteeing that only one thread can execute a method at any given time. However, this also leads to reduced performance due to synchronization overhead.

  • StringBuilder: Methods are not synchronized. This makes it more performant than StringBuffer in single-threaded environments. When using StringBuilder from multiple threads without external synchronization, incorrect results may occur, as operations can interleave.

When to use:

  • Use StringBuilder in single-threaded applications or when thread safety is ensured at a higher level. It is faster.
  • Use StringBuffer in multi-threaded applications where multiple threads may modify the same object simultaneously, and built-in thread safety is needed.

Example:

// StringBuilder in a single-threaded environment (preferable)
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("World");
System.out.println(sb.toString()); // Outputs "Hello World"

// StringBuffer in a multi-threaded environment (safer for concurrent access)
StringBuffer sbf = new StringBuffer();
// In a real multi-threaded scenario, threads would access sbf
sbf.append("Thread ").append(Thread.currentThread().getId());
System.out.println(sbf.toString()); // Will output something like "Thread 1" or "Thread 2" depending on the thread