Synchronizing on Arbitrary Objects

In the previous example, I synchronized on the object itself, i.e. this. You can synchronize on other objects too. For example, the following static method uses a simple bubble sort to sort an array of ints. The sorting code synchronizes on the array to make sure that no other thread modifies the array while it's being sorted:

  public static void bubbleSort(int[] n) {
  
    boolean sorted = false;
    synchronized(n) {
      while (!sorted) {
        sorted = true;
        for (int i=0; i < n.length - 1; i++) {
          if (n[i] > n[i+1]) {
            int temp = n[i];
            n[i] = n[i+1];
            n[i+1] = temp;
            sorted = false;
          } // end if  
       } // end for
     } // end while
   } // end synchronized
   
 } // end sort 
Here you're not worried about this object being changed by a different thread. After all, the method is static. You're worried that the array may be changed by a different thread, so that's what you synchronize.

You can synchronize arrays because they are objects, albeit a funny sort of object. You cannot synchronize primitive data types like int, float, or char.

You can synchronize strings because they're objects, but you don't need to because strings are immutable.

Also note that you don't know anything about what else is going on in the program. There may only be one thread that has access to this array. Then again, there might be dozens. Whether or not you need to synchronize a method like this requires you to know lots of details about where this method is going to be used. When you're writing general utility classes and methods, that may be used by many different programs, you must assume that different threads will call the method at the same time.


Previous | Next | Top
Last Modified November 27, 2000
Copyright 1997-1998, 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu