The synchronized keyword

Java does allow you to guarantee that no more than one thread at a time will run a method. Other threads will have to wait for the first thread to finish running. In the meantime they block, that is stop executing.

You do this by applying the synchronized keyword to the method, like this:

public class SychronizedCounter extends Counter {

  public synchronized void count() {
    int limit = i + 100;
    while (i++ != limit) System.out.println(i);
  }

}
However you don't want to synchronize lightly. This solution severely impacts performance. In general synchronized methods run three to ten times slower that the equivalent non-synchronized method.

Synchronization is not a panacea, either. There can still be thread related bugs in classes that have synchronized methods. There can also be non-thread related bugs. In fact there's one in this very class. Can you find it?


Previous | Next | Top
Last Modified December 2, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu