Java Lock variable assignment before use. Why?

前端 未结 5 1650
迷失自我
迷失自我 2020-12-06 07:11

In a lot of of the Java source, (for example LinkedBlockingDeque) I see things like this;

final ReentrantLock lock = new ReentrantLock();

publi         


        
5条回答
  •  执笔经年
    2020-12-06 08:09

    In this piece of code it doesn't matter: both examples work exactly the same. However if the instance variable lock was not final then it could make a difference as the instance variable could be changed during the locked operation: you then want to make sure that you unlock the same lock that you initially locked.

    But as lock is final, it doesn't matter: the local variable assignment in your first example is superfluous.

提交回复
热议问题