Search code examples
javamultithreadingsynchronizationstringbuffer

How does StringBuffer synchronization work?


Greetings to everyone!

I'm a bit confused as to in what way/under what circumstances StringBuffer is synchronized and prevents multi-threaded access. In the code below it prints out the letters in the for loop A 100 times then B 100 times etc... comment out the synchronized (sb){} part and it is no longer synch'd and doesn't work....

How then is the StringBuffer synchronized... under what restrictions will it work ? Could someone explain in simple terms ? Does it have to be atomic operations ?

Thanks !

John.

package threads.sync.ch13;

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

class Ex13_2 extends Thread {

static StringBuffer sb;
// StringBuilder sb;
String s;

public Ex13_2(StringBuffer sb) {

    this.sb = sb;

}

public void run() {
    synchronized (sb) {
        // incr letter then print 100 X
        sb.replace(0, sb.length(), this.s);
        for (int i = 0; i < 100; i++) {
            System.out.print(this.sb);
        }
        System.out.println();

    }

}

public static void main(String[] args) {

    // single Class Buffer per Instance...
    sb = new StringBuffer("");

    // Create Array of Multiple Thread Instances
    // and start running them...
    List<Ex13_2> e = new ArrayList<>();

    for (char c = 'A'; c <= 'D'; c++) {
        Ex13_2 t = new Ex13_2(sb);
        t.s = c + "";
        e.add(t);

    }

    for (Ex13_2 t : e) {
        t.start();
    }

}

}

Solution

  • Each method in StringBuilder is thread safe. But you are calling various methods in sequence. So each call to a method is mutually exclusive, but not the whole series of calls.

    By putting the whole series into a synchronized(sb) {} block, you make the whole series of calls mutually exclusive.