Home > Enterprise >  Why Jdk DateFormat use StringBuffer instead of StringBuilder?
Why Jdk DateFormat use StringBuffer instead of StringBuilder?

Time:10-26

I checked Jdk19 source code and I noticed that DateFormat always uses StringBuffer when formatting a Date into String. Shouldn't that be StringBuilder because it's faster?

CodePudding user response:

It's because at the time when DateFormat was written (Java 1.1) there was no class StringBuilder (which only exists since Java 1.5).

If the StringBuffer was an implementation detail this would be no problem.

But DateFormat has two methods that accept and return a StringBuffer:

Rewriting these methods to accept and return a StringBuilder would break existing code.


Please note that (as Johannes Kuhn has pointed out) the first of these two methods is specified by the abstract base class java.text.Format (also from Java 1.1), so changing this would have even greater implications.

CodePudding user response:

StringBuilder's methods are not thread safe (not synchronised) that could be the reason for using StringBuffer in the implementation of DateFormatter. Most methods of StringBuilder and StringBuffer invoke an implementation of the parent AbstractStringBuilder. StiringBuffer is similar to StringBuilder, except that many methods use lSynchronized for synchronization.

checkout the source code analysis of StringBuilders and StringBuffer.

  • Related