LinkedBlockingQueue 第一个元素丢失

LinkedBlockingQueue first elements are missing

我使用 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
        }
    }
}

有人经历过类似的事情吗?

队列是一种 FIFO(先进先出)数据结构。一旦你从队列中取出一个对象,它就不再是那个数据结构的一部分。您必须将其放回队列中。

如果您只想查看元素,则需要使用 peek()。

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

莫迪先生提到的问题

Can you please tell me the exact scenario how you are using this?Since take() and pull() are both synchronised methods but both threads might be working on same Object.So the data will should be popped out and printed by both the threads.There are chances that context switching came to the same thread and same thread calls the poll() again and you would have been looking for thread 2 in next turn