Java Synchronized methods,StringBuilder vs StringBuffer

Spread the love

————————————————————————–
http://stackoverflow.com/questions/355089/difference-between-stringbuilder-and-stringbuffer

StringBuilder is intended as a drop in replacement for StringBuffer where synchronisation is not required.
Synchronization is virtually never required. If someone wants to synchronize on a StringBuilder, they can just surround the entire block of code with a synchronized
I would argue that StringBuffer is never a good idea (unless you have an API which requires it)

Only place I see for a StringBuffer is console like output and various logging utility: many thread may output in conflict. Since you don’t want 2 output to get mixed up… but usually synchronizing at StringBuffer level is too low level, you will want to synchronize at an appender like levelm so locka answer is the best and StringBuffer should be deprecated. It would save code review time with newbies.
Good mnemonic for those who mix these two – BuFFer was First, older and therefore synchronized implementation.

Newer Builder class uses Builder pattern and is asynchronous
But StringBuffer is slower than StringBuilder. You choose the one you perfer based on what kind of applications you work on.
Another difference is that StringBuffer can be used with Matcher#appendReplacement, whereas StringBuilder cannot. This is a very annoying API difference, especially because Matcher is not thread safe so there is no need for appendReplacement to require synchronization
java.lang.StringBuffer : All methods except the Constructor are synchronized Vs

java.lang.StringBuilder : All of them are normal (non-synchronized) methods

To find more details about What actual cause the StringBuilder fails in multi threading environment I have asked a question that could be helpful

StringBuffer is synchronized, StringBuilder is not

A data race occurs when: two or more threads in a single process access the same memory location concurrently, and. at least one of the accesses is for writing, and. the threads are not using any exclusive locks to control their accesses to that memory.

————————————————————————————-
http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

Difference Between String , StringBuilder And StringBuffer Classes With Example : Java

Today we are going to understand the difference between String , StringBuilder and StringBuffer . As you will find that there are minor differences between the above mentioned classes.

String

String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed.

String  demo = ” hello ” ;
// The above object is stored in constant string pool and its value can not be modified.

demo=”Bye” ;     //new “Bye” string is created in constant pool and referenced by the demo variable
// “hello” string still exists in string constant pool and its value is not overrided but we lost reference to the  “hello”string

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronizedthat is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer(“Hello”) ;
// The above object stored in heap and its value can be changed .

demo1=new StringBuffer(“Bye”);
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe .

StringBuilder demo2= new StringBuilder(“Hello”);
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder(“Bye”);
// Above statement is right as it modifies the value which is allowed in the StringBuilder

Testing !:

package bestpractices;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
*
* @author VonTalavang
*/
public class BestPractices {

private static long tiempoInicio;
private static StringBuffer sbf;
private static StringBuilder sbu;
private static List<String> listaStrings;

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
listaStrings = new ArrayList<>();

for (int i = 0; i < 10000000; i++) {
listaStrings.add(Math.random() + “”);
}

proceso_sbf_outside_leng0();
proceso_sbf_outside_create_new_sbf();
proceso_st_plus_st();
proceso_stringbuilder();
}

private static void proceso_stringbuilder() {
System.out.print(“proceso_stringbuilder: “);
sbu = new StringBuilder();
tiempoInicio = Calendar.getInstance().getTime().getTime();
for (String st : listaStrings) {
String temp = sbu.append(st).append(Math.random()).toString();
sbu.setLength(0);
}
imprimirTiempoPasado();
}

private static void imprimirTiempoPasado() {
long tiempoAux = Calendar.getInstance().getTime().getTime();
System.out.println((tiempoAux – tiempoInicio));
tiempoInicio = tiempoAux;
}

private static void proceso_sbf_outside_leng0() {
System.out.print(“proceso_sbf_outside_leng0: “);
sbf = new StringBuffer();
tiempoInicio = Calendar.getInstance().getTime().getTime();
for (String st : listaStrings) {
String temp = sbf.append(st).append(Math.random()).toString();
sbf.setLength(0);
}
imprimirTiempoPasado();
}

private static void proceso_sbf_outside_create_new_sbf() {
System.out.print(“proceso_sbf_outside_create_new_sbf: “);
sbf = new StringBuffer();
tiempoInicio = Calendar.getInstance().getTime().getTime();
for (String st : listaStrings) {
String temp = sbf.append(st).append(Math.random()).toString();
sbf = new StringBuffer();
}
imprimirTiempoPasado();
}

private static void proceso_st_plus_st() {
System.out.print(“proceso_st_plus_st: “);
tiempoInicio = Calendar.getInstance().getTime().getTime();
for (String st : listaStrings) {
String temp = “” + st+Math.random();
}
imprimirTiempoPasado();
}
}

output:

debug:
proceso_sbf_outside_leng0: 9092
proceso_sbf_outside_create_new_sbf: 14498
proceso_st_plus_st: 8137
proceso_stringbuilder: 7301
BUILD SUCCESSFUL (total time: 58 seconds)

Using netbeans 8.2

Comments

comments

Leave a Reply