Pergunta

I would like to call a wait and notify on a different object than the one that has synchronized on a lock. Take this code for example:

Class1.foo() {
    synchronized(lock) {
        while(condition) { 
            try {
                lock.wait();
            }
        }
        lock.notify();
    }

}

I am wondering if this is equivalent to:

Class1.foo() {
    synchronized(lock) {
         Class2.bar(lock);
    }
}

Class2.bar(Object lock) {
    while(condition) {
        try {
            lock.wait();
        }
    }
    lock.notify();
}

Thanks!

Foi útil?

Solução

Monitors and synchronization are associated with objects, not variables:

Every object has an intrinsic lock associated with it .. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock [as with synchronized] ..

In the given code, it can be seen that trivially inlining the method call in the latter case results in the same objects being used in the same sequence.

Class1.foo() {
    synchronized(lock) {
        while(condition) { 
            try {
                lock.wait();
            }
        }
        lock.notify();
    }
}

Class1.foo() {
    synchronized(lock) {
    // >> inline from Class2.bar(Object lock) {
    //    where lock evaluates to the same object
        while(condition) {
            try {
                lock.wait();
            }
        }
        lock.notify();
    // << end inline }
   }
}

The above only argues for equivalency in the presented code and makes no further claim. That is, it assumes that Class2.bar is only called from Class1.foo (or is otherwise synchronized upon the same object during the invocation).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top