Java PriorityQueue:是更好的poll()然后添加()或peek()然后删除()

时间:2015-10-02 09:35:54

标签: java performance collections queue

我刚刚完成了我的网络作业队列,我对Java中PriortiyQueue的性能提出了一些小问题。

拿这段代码:

 private void performJob() {
    lock.lock();
    try {
        NetworkJob job = actions.poll();
        if (job.perform()) {
            return;
        }
        actions.add(job); //Job was a failure, add it back to the queue
    } finally {
        lock.unlock();
    }
}

如果作业失败,则作业仍然需要在队列中。所以,我的问题是:poll()然后add()peek()然后remove()

更好吗?

我个人倾向于下面的代码,但考虑到工作不应该真的失败(在大多数情况下,假设它是一个通行证)仅仅poll()更好吗?

 private void performJob() {
    lock.lock();
    try {
        NetworkJob job = actions.peek();
        if (!job.perform()) {
            return;
        }
        actions.remove(); //Job was a success,  we can remove it from the queue.
    } finally {
        lock.unlock();
    }
}

完全挑剔,可能不值得担心由于队列中很少使用的性质,但它让我感兴趣,我希望看到你的推理。

完整代码:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.util.PriorityQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public final class NetworkQueue implements Runnable {

    private final Context context;
    private final AtomicBoolean running = new AtomicBoolean(true);
    private final PriorityQueue<NetworkJob> actions = new PriorityQueue<>(5, new NetworkJobComparator());
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition jobReady = lock.newCondition();
    private final Condition networkUp = lock.newCondition();

    private ConnectionType connection = ConnectionType.NONE;

    public NetworkQueue(Context context) {
        this.context = context;
        context.registerReceiver(new NetworkListener(),
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    public void run() {
        try {
            while (running.get()) {
                waitJobAvailable();
                waitNetworkUp();
                performJob();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void setNetwork(ConnectionType net) {
        lock.lock();
        try {
            connection = net;
            if (connection != ConnectionType.NONE) {
                networkUp.signal();
            }
        } finally {
            lock.unlock();
        }
    }

    private void waitNetworkUp() throws InterruptedException {
        lock.lock();
        try {
            while (connection != ConnectionType.NONE) {
                networkUp.await();
            }
        } finally {
            lock.unlock();
        }
    }


    private void waitJobAvailable() throws InterruptedException {
        lock.lock();
        try {
            while (actions.isEmpty()) {
                jobReady.await();
            }
        } finally {
            lock.unlock();
        }
    }

    private void performJob() {
        lock.lock();
        try {
            NetworkJob job = actions.peek();
            if (!job.perform()) {
                return;
            }
            actions.remove();
        } finally {
            lock.unlock();
        }
    }

    public boolean addJob(NetworkJob job) {
        lock.lock();
        try {
            if (this.actions.contains(job)) {
                return false;
            }
            this.actions.add(job);
            this.jobReady.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }

    public void end() {
        this.running.set(false);
    }

    private class NetworkListener extends BroadcastReceiver {

        ConnectivityManager conn = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);

        @Override
        public void onReceive(Context context, Intent intent) {
            NetworkInfo networkInfo = conn.getActiveNetworkInfo();
            if (networkInfo == null) {
                setNetwork(ConnectionType.NONE);
                return;
            }
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                setNetwork(ConnectionType.WIFI);
                return;
            }
            setNetwork(ConnectionType.ANY);
        }
    }

}

1 个答案:

答案 0 :(得分:1)

在OpenJDK和OracleJDK的标准基于堆的PriorityQueue实现中,peek()调用非常快:

public E peek() {
    return (size == 0) ? null : (E) queue[0];
}

那是因为堆根始终是最少的元素。相反,删除和添加操作可能非常昂贵,因为它们可能需要重组堆。因此,peek/remove解决方案可能会更快。

在我的库中,我有一个算法可以从未排序的输入中选择n个最少的元素。我使用PriorityQueue实现了它,它最多保留了迄今为止发现的最少n个元素。第一个实现就像add/poll。当我updated使用peek时,性能得到了显着提升(在某些测试中最高可达10倍)。