Static Methods (Synchronization Details)

What about using wait() and notify() in a static method? The wait() and notify() methods are nonstatic methods of the Object class. Since static methods cannot call nonstatic methods without an object reference, static methods cannot call the wait() and notify() methods directly. But there is nothing preventing us from instantiating an object for the sole purpose of using it as a waiting point. This is just like the technique we used earlier when we tried to grab an object lock from a static method.

Using an actual object also allows the wait() and notify() methods from static and nonstatic methods to interoperate, much like using the synchronized block mechanism on a common object can allow static and nonstatic methods to interoperate. The following versions of staticWait() and staticNotify() could be called from both static and nonstatic methods:

public class MyStaticClass {
    static private Object obj = new Object();

    public static void staticWait() {
        synchronized (obj) {
            try {
                obj.wait();
            } catch (Exception e) {}
        }    
    }

    public static void staticNotify() {
        synchronized (obj) {
            obj.notify();
        }
    }
}

It’s rare for threads that are executing static methods to interoperate with threads that are executing nonstatic methods in this manner. Nevertheless, by having a static version of the wait() and notify() methods, we allow interoperability to occur. These methods have different names because they have the same signatures as the wait() and notify() methods.

Get Java Threads, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.