privatebooleaninternalLock(long time, TimeUnit unit)throws Exception { /* Note on concurrency: a given lockData instance can be only acted on by a single thread so locking isn't necessary */
try { //开始创建节点 ourPath = driver.createsTheLock(client, path, localLockNodeBytes); //根据创建节点进行过滤并且判断是否是第0个元素 hasTheLock = internalLockLoop(startMillis, millisToWait, ourPath); } catch ( KeeperException.NoNodeException e ) { // gets thrown by StandardLockInternalsDriver when it can't find the lock node // this can happen when the session expires, etc. So, if the retry allows, just try it all again // 重试,这块在internalLockLoop内部判断ourPath是否存在children List内时会 // 抛出NoNodeException,这就是解决某一节点同步延迟的情况 if ( client.getZookeeperClient().getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMillis, RetryLoop.getDefaultRetrySleeper()) ) { isDone = false; } else { throw e; } } }
@Override publicvoidrelease()throws Exception { /* Note on concurrency: a given lockData instance can be only acted on by a single thread so locking isn't necessary */ Thread currentThread = Thread.currentThread(); LockData lockData = threadData.get(currentThread); //并未获得过锁 if ( lockData == null ) { thrownew IllegalMonitorStateException("You do not own the lock: " + basePath); } //lockCount-1 int newLockCount = lockData.lockCount.decrementAndGet(); //如果-1后的结果依然大于0,说明是重入的情况,所以直接返回等待最后一个release if ( newLockCount > 0 ) { return; } //已经释放过锁或者其他的情况 if ( newLockCount < 0 ) { thrownew IllegalMonitorStateException("Lock count has gone negative for lock: " + basePath); } try { //释放锁 internals.releaseLock(lockData.lockPath); } finally { //从threadData中将当前线程remove threadData.remove(currentThread); } }