Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

offer
java
communitycreator

What is the ConcurrentLinkedQueue.offer() method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The ConcurrentLinkedQueue is thread-safe unbounded queue. The elements are ordered by FIFO (First-In-First-Out). The elements are inserted at the tail (end) and retrieved from the head (start) of the queue. Null elements are not allowed as elements of the queue. We can use the ConcurrentLinkedQueue when multiple threads are sharing a single Queue.

The offer method can be used to add an element to the tail of the ConcurrentLinkedQueue object.

Syntax

public boolean offer(E e)

Parameters

The offer method takes the element to be added to the ConcurrentLinkedQueue as a parameter. This method throws a NullPointerException if the argument is null.

Return value

The offer method returns true if the element is added to the queue.

Code

The code below demonstrates how to use the offer method.

import java.util.concurrent.ConcurrentLinkedQueue;
class Offer {
    public static void main( String args[] ) {
      ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
      queue.offer("1");
      System.out.println("The queue is " + queue);

      queue.offer("2");
      System.out.println("The queue is " + queue);

    }
}

Explanation

In the above code:

  • In line 1, we import the ConcurrentLinkedQueue class.

  • In line 4, we create a ConcurrentLinkedQueue object with the name queue.

  • In line 5, we use the offer method of the queue object to add an element (1) to the end of the queue. Then, we print it.

  • In line 8, we use the offer method to add an element (2) to the end of the queue. Finally, we print it.

RELATED TAGS

offer
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring