The only case when the LinkedBlockingQueue methods will return immediately is if we use a bounded queue and this queue is empty or full. The LinkedBlockingQueue will block these operations. While ConcurrentLinkedQueue poll and offer as completely lock-free. However, because of different internal implementations, they behave differently. These queues use the Queue as the base interface and implement the poll and offer methods. It does not block the accessing thread when the queue is empty and returns null So, it blocks the accessing threads when the queue is empty It uses CAS (Compare-And-Swap) for its operations The put/take operations use the first lock type, and the take/poll operations use the other lock type In the two-lock queue algorithm mechanism, LinkedBlockingQueue uses two different locks – the putLock and the takeLock. It relies on the Michael & Scott algorithm for non-blocking, lock-free queues It implements its locking based on a two-lock queue algorithm It is an unbounded queue, and there is no provision to specify the queue size during creation It is an optionally bounded queue, which means there are provisions to define the queue size during the creation It is a non-blocking queue and does not implement the BlockingQueue interface It is a blocking queue and implements the BlockingQueue interface Therefore, the take method blocks the calling thread.Īlthough both of these queues have certain similarities, there are substantial characteristics differences, too: Feature In the above code snippet, we are accessing an empty queue. LinkedBlockingQueue queue = new LinkedBlockingQueue() Similarly, if the queue is empty, then accessing an element blocks the calling thread: ExecutorService executorService = Executors.newFixedThreadPool(1) If the queue is full, then adding a new element will block the accessing thread unless there is space available for the new element. The LinkedBlockingQueue class implements the BlockingQueue interface, which provides the blocking nature to it.Ī blocking queue indicates that the queue blocks the accessing thread if it is full (when the queue is bounded) or becomes empty. We can create a LinkedBlockingQueue from an existing collection as well: Collection listOfNumbers = Arrays.asList(1,2,3,4,5) īlockingQueue queue = new LinkedBlockingQueue(listOfNumbers) However, if there is no memory left, then the queue throws a. Therefore, the queue can grow dynamically as elements are added to it. BlockingQueue unboundedQueue = new LinkedBlockingQueue() Īn unbounded queue implies that the size of the queue is not specified while creating.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |