shenjianeng commented on PR #7582:
URL: https://github.com/apache/rocketmq/pull/7582#issuecomment-1835681345

   > 在外面没什么问题。参考:https://juejin.cn/post/7269962653795270671
   
   看下 jdk 
的官方文档建议吧,https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantLock.html
   
   > It is recommended practice to *always* immediately follow a call to `lock` 
with a `try` block, most typically in a before/after construction such as:
   >
   > ```java
   >  class X {
   >    private final ReentrantLock lock = new ReentrantLock();
   >    // ...
   > 
   >    public void m() {
   >      lock.lock();  // block until condition holds
   >      try {
   >        // ... method body
   >      } finally {
   >        lock.unlock()
   >      }
   >    }
   >  }
   > ```
   
   作为开源项目,带头做好榜样。
   
   而且上面掘金文章结尾有几句话:
   
   > 1. 最好是把 lock.lock() 加锁方法写到 try 外面,是一种规范,而不是强制。
   >
   > 2. 如果你非要写到 try 里面,那么写到 try 语句块的第一行,或者 lock 加锁方法前面不会存在可能出现异常的代码。
   >
   > 3. 最后,如果你代码中加锁放到了 try 语句里,麻烦参考第 1 点
   
   
   严格来讲,1 和 2 的结论,可能在 ReentrantLock 这个实现下是没问题的,但 lock 是接口,会有任意实现多种实现。
   
   在不同的实现下,lock.lock()  方法抛出异常是很有可能的,因此不能放在 try 当中。


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@rocketmq.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to