Search code examples
javaconcurrencyblockingqueue

BlockingQueue offer method doesn't add item to list sometime


I am using BlockingQueue in a multi threading system where a synchronized block adds items to the list. Sometimes it does not add items to the list, items that it misses are random.I tried to add following line to the code and then it never missed any item.

list.forEach(item -> logger.info(" In list "+item));

I feel this behaviour is kind of strange. Can someone please help me figure out how can I resolve this problem of missing file? I do not want to unnecessarily iterate over the entire list. Am I missing something in this?


Solution

  • The documentation for offer says it might fail sometimes.

    Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.

    If you're okay to block when you try to add, use put

    Inserts the specified element into this queue, waiting if necessary for space to become available.