new Class vs new Object for the lock in java

Vitalii :

Is there any difference between a lock created from a class and from an object?

class AWTInvocationLock {}
Object lock = new AWTInvocationLock();

public void foo(){
    synchronized (lock) {
        // ...
    }
}

public Object lock = new Object();
public void bar(){
    synchronized (lock) {
        // ...
    }
}

In java.awt I see this code and I'm wondering about the idea of class AWTInvocationLock {} instead of just new Object()

static void invokeAndWait(Object source, Runnable runnable)
    throws InterruptedException, InvocationTargetException
{
    // ...

    class AWTInvocationLock {}
    Object lock = new AWTInvocationLock();

    InvocationEvent event =
        new InvocationEvent(source, runnable, lock, true);

    synchronized (lock) {
        Toolkit.getEventQueue().postEvent(event);
        while (!event.isDispatched()) {
            lock.wait();
        }
    }

    //...
}
Spara :

It's better to describe the code a bit:

class AWTInvocationLock {}
    Object lock = new AWTInvocationLock();

    InvocationEvent event =
        new InvocationEvent(source, runnable, lock, true);

    synchronized (lock) {
        Toolkit.getEventQueue().postEvent(event);
        while (!event.isDispatched()) {
            lock.wait();
        }
    }

The lock object reference is escaping the local scope. A ref is stored in the InvocationEvent object:

InvocationEvent event =
            new InvocationEvent(source, runnable, lock, true);

The EventQueue's dispatch thread is listening for posted Event objects. The thread invokes a dispatch() method on each event. I haven't looked at the source code, but I guess that the InvocationEvent.dispatch() method pseudo-code looks like this;

 1. synchronize(lock)
 2. runnable.run() -- store any exceptions to a "throwable" reference variable
 3. lock.notify()

So the EventQueue dispatch thread calls notify() on the lock object, which releases the thread that calls invokeAndWait() from the wait() call in the next line.

Is there any difference between a lock created from a class and from an object?

AWTInvocationLock is a named inner class with method scope. I've never actually seen one in the wild. Its a really obscure part of the language, and one that almost no one I know is aware of. I would never use one because of that, and because Javadoc doesn't even recognize these and won't generate documentation for them!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=80943&siteId=1