Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
Threads and Concurrency » Discussions

Why doesn't static synchronized work here?

public class Babble
{
private static synchronized void say(String s)
{
System.out.print(s);
}
public static void main(String s)
{
Thread letters=new Thread(){
public void run()
{say("a");say("b");say("c");}
}
};
Thread numbers=new Thread(){
public void run()
{say("1");say("2");say("3");}
}
};
letters.start();
numbers.start();
}
}


Since the say() method is static and synchronized it can be accessed by a single thread at a time. Can a1b23c be a possible output?

Your program should not compile as it has more closing braces than opening braces. Proper indentation is the key - not only it makes your code readable, but also helps you figure out the scope errors. I have attempted to indent your code and correct the problem with braces:


public class Babble {
	
  private static synchronized void say(String s) {
    System.out.print(s);
  }
	
  public static void main(String s) {
    Thread letters=new Thread(){
      public void run() {
        say("a");say("b");say("c");
      }
    };

    Thread numbers=new Thread(){
      public void run() {
        say("1");say("2");say("3");
      }
    };
    
    letters.start();
    numbers.start();
    
  }
}


Does this look correct?


Then yes, a1b23c is a possible outcome.


It's true that only one thread can access the say() method at a time. But that doesn't make any difference here because the only statement protected here is System.out.print(s);, which is a single statement that only just prints the value of the parameter s. Protecting that line doesn't make much noticeable difference.


Let's see the flow of the program. We have two threads as letters and numbers. We don't know which one will run first, because it's up to the thread scheduler to decide. For the sake of clarity, let's consider if the thread scheduler has picked the letters thread to run first. In that case, we have the first statement, which is say("a");. Now it has to go to the say(-) method. As it goes into that method, it takes the monitor lock of the class Babble in a way that no other thread would be able to access the say(-) method, until it completes the method.


Now if we have the letters thread started meanwhile, it could reach its first statement, which is say("1");. But it can't reach the say method until the first thread completes the execution of that method. But as soon as the first thread completes the execution of the say method, the second thread can go in, and print '1'.


In summary, even though the say(-) method is synchronized, it only makes one thread access the say method at a time. As soon as one thread exists form the method's scope, the chance would be given for any other thread (decided by the thread scheduler) to take the next call to that method.


Does that make it clear?

Yes, I got it now. Thank you !!

ExamLab © 2008 - 2017