Optimize the Implementation of preferred leader #22
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Purpose(目标)
This PR is to polish preferedleader.
优化preferedleader
Changelog(修改记录)
The current situation is that REJECT_TAKING_LEADERSHIP may occur even if preferred leader is not set. So currTerm is initially set to 0 and termToTakeLeadership is initially set to -1, which ensures that they will not be the same under normal circumstances.
在测试的时候出现即使没有设置preferred leader,日志中仍然出现了REJECT_TAKING_LEADERSHIP。这是因为当前currTerm初始时设置为-1,而termToTakeLeadership设置为0,当term增加,两者会相等。因此设置currterm初始为0,termToTakeLeadership初始为-1,确保两者正常情况下不会相等。
Role may be follower when term < TermToTakeLeadership in check function , it should not return directly. For example, The node may receive heartbeat before term increase as a candidate, then it will be follower and should return TAKE_LEADERSHIP_FAILED.
在TakeLeadershipTask的check方法中,当term <TermToTakeLeadership时,直接返回。但有可能出现这样的情况:抢主的candidate节点在提升自己的term之前收到了心跳,从而变成了follower,此时满足term < TermToTakeLeadership,这是应该算是抢主失败,所以应该返回TAKE_LEADERSHIP_FAILED。(这个情况出现的概率比较小)
When a node takeleadership, it refuses to vote for other nodes only if the LedgerEndTerm of the two nodes is consistent and the LedgerEndIndex of the current node is greater than or equal to that of other node.
当一个节点正在抢主,当前如果日志高度相等则拒绝投票。更加保险的情况下先比较最后一个日志条目的term是否相等,然后再比较日志高度是否相等,都相等再拒绝投票。
Add volatile for some variables to ensure visibility
为一些变量加上volatile属性确保可见性。