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

前端 未结 6 2214
北荒
北荒 2020-12-03 13:09

A Lock is always followed by a try/finally block, why?

ReentrantReadWriteLock readWriteLockBitmap = new ReentrantReadWriteLock();
Lock read = readWriteLockBi         


        
6条回答
  •  情歌与酒
    2020-12-03 13:19

    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();
    }
    

提交回复
热议问题