Threads – Why a Lock has to be followed by try and finally

Because a try/finally block is the only way to guarantee that a segment of code is executed after another completes.

You ask why not do this:

public void function1(){
    read.lock();
    this.getSharedInt();
    read.unlock();
}

What happens when this.getSharedInt() throws an exception? Then your read.unlock() line will not be executed, causing program deadlock. Sure, it may be 100% certified to not throw an exception right now, but what happens when you refactor to store that shared int in a file or database?

Finally, don’t forget that try/finally also accounts for errors, which can be thrown by the runtime at almost any line in a program, even if the function is guaranteed to not throw any exceptions.

Note that this code would also work, but it swallows the exception. Using finally instead allows the exception to propagate normally, while still unlocking under all conditions.

public void function2(){
    read.lock();
    try {
        this.getSharedInt();
    } catch(Throwable t) {}
    read.unlock();
}

Leave a Comment