How do I use a synchronized block in a static method?
Author: Deron Eriksson
Description: This Java tutorial describes how to use a synchronized block in a static method.
Tutorial created using:
Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)
It's possible to synchronize a static method. When this occurs, a lock is obtained for the class itself. This is demonstrated by the static hello() method in the SyncExample class below. When we create a synchronized block in a static method, we need to synchronize on an object, so what object should we synchronize on? We can synchronize on the Class object that represents the class that is being synchronized. This is demonstrated in the static goodbye() method of SyncExample. We synchronize on SyncExample.class. SyncExample.javapackage com.cakes; public class SyncExample { public static void main(String[] args) { hello(); goodbye(); } public static synchronized void hello() { System.out.println("hello"); } public static void goodbye() { synchronized (SyncExample.class) { System.out.println("goodbye"); } } } Note that in this example, the synchronized block synchronizes on the SyncExample Class object. When using a synchronized block, we can also synchronize on another object. That object will be locked while the code in the synchronized block is being executed. |