PriorityBlockingQueue阻塞太长时间

时间:2015-05-22 16:19:06

标签: java multithreading

我使用PriorityBlockingQueue存储功能的tf-idf分数。由于这部分是多线程的,我使用synchronized块来处理并发:

long ticAdd = 0;
long tocAdd = 0;
long ticPoll = 0;
long tocPoll = 0;
long ticAll = System.nanoTime();

PriorityBlockingQueue<TfIdfScore> allScores = sharedFeatureNameToScores.get(featureName);

// ..

synchronized (allScores) {  

    ticAdd = System.nanoTime();
    allScores.add(instanceScore);
    tocAdd = System.nanoTime();

    int allScoresSize = allScores.size();

    ticPoll = System.nanoTime();
    while( allScoresSize > scoresToKeepCount) {                 
        allScores.poll();                               
        allScoresSize = allScores.size();
    }
    tocPoll = System.nanoTime();

    long tocAll = System.nanoTime();

    if( ((tocAll - ticAll) /(1e6)) > 10 ) {
        System.out.println("---\nallScores.size " + allScores.size());
        System.out.println("add duration: " + ((tocAdd - ticAdd) /(1e6)) + "ms");
        System.out.println("poll duration: " + ((tocPoll - ticPoll) /(1e6)) + "ms");
        System.out.println("overall duration: " + ((tocAll - ticAll) /(1e6)) + "ms");               
    }
} // end synchronized

问题是,这似乎有时会阻塞很长一段时间,我只是无法找出原因。队列不是很大或任何东西,但正如你在我的输出中所看到的那样,它阻塞的时间相当长(有时):

---
allScores.size 471
add duration: 3.34E-4ms
poll duration: 12.02297ms
overall duration: 12.023402ms
---
allScores.size 471
add duration: 3988.91183ms            <===
poll duration: 0.002303ms
overall duration: 3988.915091ms
--
allScores.size 471
add duration: 4.69E-4ms
poll duration: 4002.275955ms          <===
overall duration: 4002.276525ms   

为什么会这样?你可以想象这会让我的程序减慢很多......

另一件奇怪的事情是,有时添加部分,有时民意调查部分需要更长的时间。

1 个答案:

答案 0 :(得分:0)

我建议删除对象监视器上的同步,而不是要求您使用ConcurrentLinkedQueue换行或使用synchronizedCollection(Collection c)依赖同步。

这可能会减少使用通用对象锁定时的阻塞延迟。