LinkedBlockingQueue缺少第一个元素

时间:2016-07-26 12:40:16

标签: java concurrency cmis

我使用LinkedBlockingQueue进行应用程序的隐式同步,但是如果我使用queue.take()queue.poll(),那么在从队列中获取后,前几个元素会以某种方式丢失。我已经检查过它是否是同一个对象而且是。

这是我的代码:

for ( QueryResult result : tmpPage ) {
    String objectId = result.getPropertyValueByQueryName( "cmis:objectId" );
    writer.writeFile(objectId ); //Only for debugging reasons to 
                                 //compare the input and the output
    try {
        batchJobs.offer( new Node( objectId ), 1,TimeUnit.HOURS);
    } catch(Exception e) {
        errorLogger.error( e.getMessage() );
    }
}

我拍摄或投票的地方

Node node = null;
while ( !nodes.isEmpty() ) {
    while((node = nodes.take())!=null ) {
        writer.writeFile( node.getObjectID() ); // Only for debugging reasons
        if ( node != null ) {
            //Do some stuff
        }
    }
}

有人经历过类似的事吗?

3 个答案:

答案 0 :(得分:2)

队列是FIFO(先进先出)数据结构。从队列中获取对象后,它将不再是该数据结构的一部分。你必须把它放回队列。

如果你只想查看元素,你可能想要使用peek()。

答案 1 :(得分:2)

在队列中,take()和poll()方法检索数据并将其从队列中删除。这可能是您丢失数据的原因。如果要检索数据但不想删除它,请使用peek()。

答案 2 :(得分:0)

莫迪先生提到了这个问题。

  

你能告诉我你如何使用它的确切场景吗?因为take()和pull()都是同步方法,但两个线程都可能在同一个Object上工作。所以数据将被弹出并打印出来两个线程。上下文切换有可能来到同一个线程,同一个线程再次调用poll(),你可能会在下一个回合中寻找线程2

相关问题