1

I am trying to learn basic concepts of Java 8 Concurrent Programming and can not understand the Unlock with return in a demo snippet here : http://www.javatips.net/api/thinking-java-master/src/main/java/ch21concurrent/examples/ConditionBoundedBuffer.java

// BLOCKS-UNTIL: notEmpty
public  T take() throws InterruptedException {
    lock.lock();
    try {
        while (count == 0)
            notEmpty.await();
        T x = items[head];
        items[head] = null;
        if (++head == items.length)
            head = 0;
        --count;
        notFull.signal();
        return x;         // <<< RETURN without UNLOCK ? <<<
    } finally {
        lock.unlock();
    }
}

I read about the motivation try / finally for a secure Unlock, but what about the 'return x' here, is the monitor proc. then unlocked with this return ?

rjdkolb
  • 10,377
  • 11
  • 69
  • 89
fmatz
  • 21
  • 1
  • 2
  • No. Why would it be unlocked with the return? – JB Nizet Aug 19 '17 at 18:02
  • 3
    It *is* unlocked. That's what the `finally` block does. Learn more about `finally` here: [The Java™ Tutorials - The finally Block](https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html). First sentence says it all: *The finally block **always** executes when the try block exits.* That means, even when caused by `return`. – Andreas Aug 19 '17 at 18:03
  • Interesting and confused me a bit, that means: At first finally and then 'return x' – fmatz Aug 19 '17 at 18:14

0 Answers0