4

In Java Docs it says, StringBuffer's methods are synchronized. Then why do I still need to manually synchronize the StringBuffer in the example given in this question: here

I read somewhere that it is not worthy of using StringBuffer over StringBuilder because it (StringBuffer) is slower than StringBuilder. In this way, these two are same like Vector and ArrayList.

But I was wondering, why do we call it (StringBuffer or Vector) a Thread Safe classes, when we still need to manually enclose them in synchronized block like in the example mentioned in above link. Why can't I rely on them. Can anyone explain & clear my doubts.

Is there any way to check StringBuffer is really a Thread Safe class.

Community
  • 1
  • 1
JPG
  • 1,247
  • 5
  • 31
  • 64

2 Answers2

3

The methods in StringBuffer are internally synchronised, which means that if two threads append a String to a buffer at the same time then the buffer won't interleave the strings; it will append one then the other.

The example you link synchronises itself on the string buffer instance, which is a totally different thing.

Qwerky
  • 18,217
  • 6
  • 44
  • 80
  • if I comment the `synchronized` block, then threads should not interfere each other during `setCharAt()` method. Isn't the `setCharAt()` method synchronized in `StringBuffer` class. But the scene is opposite i.e. threads do interfere during `setCharAt()`, when I comment `synchronized` block. – JPG Dec 03 '14 at 10:03
0

When you use this

synchronized(sb) 
    {
        for(int i=1;i<=10;i++){
            System.out.println(i+" : "+sb.charAt(0));
        }
        sb.setCharAt(0, (char) (sb.charAt(0)+1));
    }  

you are synchronizing entire block (ie when thread 1 uses this block no other thread should be used until completion of thread1)
If you remove synchronized , at any point of time thread1 may release the lock , so thread2 or thread 3 may change its data

LMK
  • 2,882
  • 5
  • 28
  • 52