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 Counter {

  private int count = 0;

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


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 | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
Last Modified December 2, 1997