找到你要的答案

Q:Most efficient way to process multiple callbacks into one receiver function

Q:处理多个回调到一个接收器功能的最有效的方法

I have a async API that provides the output via a callback method.

Now, I have to call this API N number of times simultaneously and then wait for N number of hits/callbacks to the callback method.

In order to achieve this, I have currently used a counter and synchronized the method.

@Override
    public synchronized void onResponseReceived() {
       receivedCount++;


        if (receivedCount == totalCount){
            onCallbacksComplete();
        }
    }

I was wondering, if there is a faster way to achieve the above?

Thanks.

我有一个异步API提供的输出通过一个回调方法。

现在,我必须调用这个函数N次数的同时,然后等待N点击次数/回调回调方法。

为了达到这个目的,我目前使用了一个计数器和同步的方法。

@Override
    public synchronized void onResponseReceived() {
       receivedCount++;


        if (receivedCount == totalCount){
            onCallbacksComplete();
        }
    }

我想知道,如果有一个更快的方式来实现上述?

谢谢.

answer1: 回答1:

Using AtomicInteger.

AtomicInteger receivedCount= new AtomicInteger();
@Override
public void onResponseReceived() {
    if (receivedCount.incrementAndGet() == totalCount){
        onCallbacksComplete();
    }
}

or

AtomicInteger receivedCount= new AtomicInteger(totalCount);
@Override
public void onResponseReceived() {
    if (receivedCount.decrementAndGet() == 0){
        onCallbacksComplete();
    }
}

This avoids the synchronization.

使用AtomicInteger。

AtomicInteger receivedCount= new AtomicInteger();
@Override
public void onResponseReceived() {
    if (receivedCount.incrementAndGet() == totalCount){
        onCallbacksComplete();
    }
}

AtomicInteger receivedCount= new AtomicInteger(totalCount);
@Override
public void onResponseReceived() {
    if (receivedCount.decrementAndGet() == 0){
        onCallbacksComplete();
    }
}

这避免了同步。

answer2: 回答2:

If you are synchronizing the method only to ensure the accuracy of the totalCount variable, you can alternatively use the Atomic Integer class for the variable, which is thread safe and provide that functionality for you. You could then remove the synchronized modifier for the onResponseReceived method This would make you synchronization block smaller and provide better performance.

You may want to use the Atomic Integer class on the received count as well.

I hope this helps

If you are synchronizing the method only to ensure the accuracy of the totalCount variable, you can alternatively use the Atomic Integer class f或 the variable, which is thread safe and provide that functionality f或 you. You could then remove the synchronized modifier f或 the onResponseReceived method This would make you synchronization block smaller and provide better perf或mance.

您可能希望在接收的计数上使用原子整数类。

我希望这有助于

java  callback  synchronization