views:

327

answers:

4

I'm coming from .NET world, and unfortunately looking Java source with .NET's eyes.

Following code is from Android Apps (though not Android specific at all):

    private class Worker implements Runnable {
        private final Object mLock = new Object();
        private Looper mLooper;

        Worker(String name) {
            Thread t = new Thread(null, this, name);
            t.start();
            synchronized (mLock) {
                while (mLooper == null) {
                    try {
                        mLock.wait();
                    } catch (InterruptedException ex) {
                    }
                }
            }
        }

        public Looper getLooper() {
            return mLooper;
        }

        public void run() {
            synchronized (mLock) {
                Looper.prepare();
                mLooper = Looper.myLooper();
                mLock.notifyAll();
            }
            Looper.loop();
        }

        public void quit() {
            mLooper.quit();
        }
    }

I'm not precisely clear with how "synchronized" works. First I thought that synchronized is locking mLock object, but then if after 't.start()' constructor thread enters sync block first, it would block it at mLock.wait(), and implicitly block thread "t" by blocking it from entering synchronized block.

This is obviously wrong, because my phone rings as supposed :)

Next thought is that synchronize synchronizes "code block" (in which case, there two synchronized block are independent => threads can enter two different sync block at same time without restriction), and that fitted perfectly...

... until my coleague told me that "mLock.wait()" releases lock on mLock and enables other thread to enter critical section on mLock in same time.

I'm not sure if I was clear enough, so will gladly answer any further questions on this.

thanx

+6  A: 

Check out the javadoc on Object.wait(). It's "magic" in that it drops the monitor that was acquired when entering the synchronized {} block. That allows another thread to acquire the monitor and call Object.notify().

When another thread calls notify() to wake the waiting thread from its wait() call, the waiting thread re-acquires the monitor and will block until it can. So the monitor is only dropped for the duration of the wait() call.

John M
This is in fact the key ingredient to understand synchronization in Java: `wait()` *releases* the lock. Everything became crystal-clear as soon as I fully understood that.
Bombe
OK... It's more clear now :)One more question:Let's say for example that in run()'s sync block, there are few more lines after line 'mLock.notifyAll()'.If I understood all correctly, constructor's thread won't continue with it's code execution not immediately after run()'s notifyAll, but only after run()'s thread leaves sync block?
Jox
As mentioned in the notify() javadoc, the notify() caller doesn't release the monitor until it normally would (exiting synchronized block or whatever). So the newly-awakened wait() thread is blocked until it can re-acquire the monitor. That can't happen until the notify() caller releases it. So the code following notify() before the end of the synchronized block definitely runs before any other thread aquires the monitor.
John M
+1  A: 

synchronized uses object monitors. Calling wait() on the object atomically releases the object monitor (for otherwise no other thread could ever take the monitor and issue a notify to the waiter(s)).

+1  A: 

Yes. If you read the description of the wait() method, you'll learn that it causes the thread to release the lock and block until another thread invokes notify or notifyAll on the lock. The current thread waits until it can re-acquire the lock, and once it does, it continues execution.

The code shown follows poor practice, however, because it "publishes" (that is, it makes the object accessible to other threads) the Worker instance before it is fully constructed. The use of additional barriers in this method, combined with the private nature of the class, probably make this case safe, but in general, it is not.

erickson
A: 

Let me explain:

The constructor launches a new thread that will execute the run() method. This new thread will obtain a new Looper object, store it in the mLooper field and then run the Looper message loop. In between it will notify() the first thread that mLooper has been set.

The first thread will therefore return from the constructor only after mLooper has been set which means that processing of Looper.loop(), by the 2nd thread, is bound to start shortly/has already started.

Itay