gpt4 book ai didi

java - 为什么在zookeeper WorkerSender中使用poll()而不是take()

转载 作者:行者123 更新时间:2023-12-02 09:20:47 24 4
gpt4 key购买 nike

我一直在阅读zookeeper源代码,发现当从FastLeaderElection.WorkerSender中的队列中获取ToSend消息时,他们使用poll() 而不是 take()。为什么?

poll() 更好吗?

搜索 git 历史记录,我发现它开始使用 take(),所以改为 poll() 肯定是有原因的。

public void run() {
while (!stop) {
try {
ToSend m = sendqueue.poll(3000, TimeUnit.MILLISECONDS);
if (m == null) {
continue;
}
process(m);
} catch (InterruptedException e) {
break;
}
}
LOG.info("WorkerSender is down");
}

最佳答案

TL;DR:检查停止标志。

<小时/>

ZOOKEEPER-498进行了更改:FastLeaderElection.java的差异

旧代码:

class WorkerReceiver implements Runnable {

QuorumCnxManager manager;

WorkerReceiver(QuorumCnxManager manager) {
this.manager = manager;
}

public void run() {

Message response;
while (true) {
// Sleeps on receive
try{
response = manager.recvQueue.take();

// Receive new message
LOG.debug("Receive new message.");

新代码:

class WorkerReceiver implements Runnable {
volatile boolean stop;
QuorumCnxManager manager;

WorkerReceiver(QuorumCnxManager manager) {
this.stop = false;
this.manager = manager;
}

public void run() {

Message response;
while (!stop) {
// Sleeps on receive
try{
response = manager.recvQueue.poll(3000, TimeUnit.MILLISECONDS);
if(response == null) continue;

// Receive new message
LOG.debug("Receive new message.");

they use poll() instead of take(). Why ?

这样他们就可以每 3 秒检查一次新的 stop 标志

关于java - 为什么在zookeeper WorkerSender中使用poll()而不是take(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58705093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com