Search code examples
javamultithreadingthread-safetysynchronized

Method synchronized , but code produces random result due to non-serialized thread behaviour


Here is my code:

public class ThreadDemo {

public static void main(String args[]) throws Exception {
    Printer[] printers = new Printer[5];
    printers[0] = new Printer("@base");
    printers[1] = new Printer("#try");
    printers[2] = new Printer("!test");
    printers[3] = new Printer("^hello");
    printers[4] = new Printer("*world");

    for (Printer x : printers) {
        x.start();
    }

    try {
        for (Printer y : printers) {
            y.join();
        }
    } catch (InterruptedException e) {
        System.out.println(e);
    }
  }
}

class Printer extends Thread {
public Printer(String name) {
    super(name);
}

public void run() {
    print();
}

public synchronized void print() {
    for (int i = 0; i < 10; i++) {
        System.out.print(getName().charAt(0));
        try {
            sleep(100);
        } catch (InterruptedException e) {
            System.out.println(e + " occured");
        }
    }
  }
}

It results in

@^!#**@^!#*#@!^@*#^!#^!*@^*@!#@!#*^@#^!*!@^#*#@*^! 

My expectation is that all symbols would be serialized as @@@@@^^^^^ based on which thread starts first.

Calling sleep() would let other threads to proceed until sleeptime of current thread , but i guess that should not be the case with synchronized method.


Solution

  • The synchronised doesn't come into play here.

    That keyword makes sure that you can't invoke the same method on the same object in parallel.

    You are invoking it on different objects, therefore the result would be the same even without the keyword in place!

    ( I rather assume that the result you see is in fact caused by using println() here. That is a "really slow" operation that introduces "de facto" synchronisation when used by threads that are super-quick doing all their other work. I am trying to find some additional information about that, but that might take some more time )