Skip to content

Created offer entry for java queue interface #7407

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions content/java/concepts/queue/terms/offer/offer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
Title: 'offer()'
Description: 'Inserts the specified element into the queue if possible without violating capacity limits.'
Subjects:
- 'Code Foundations'
- 'Computer Science'
Tags:
- 'Elements'
- 'Queues'
CatalogContent:
- 'learn-java'
- 'paths/computer-science'
---

The **`.offer()`** method is part of the Java `Queue` interface and inserts an element at the end of the queue. It returns `true` if the element was added successfully, or `false` if the queue is at capacity and cannot accept new elements.

Unlike the `add()` method, which throws an exception when the queue is full, `offer()` fails gracefully, making it useful when there is a need to handle capacity limits without triggering exceptions.

## Syntax

```pseudo
queue.offer(element)
```

**Parameters:**

- `element`: The element to be inserted to the queue.

**Return value:**

- Returns `true` if the element was added successfully, `false` if the queue is full.

The `offer()` method is non-blocking, meaning it returns immediately if the queue is full. Instead of throwing an exception when capacity is reached, it returns `false`, making it safer for capacity-aware operations. Its behavior may vary between bounded and unbounded queue implementations.

## Example: Using `offer()` in a Print Job Queue System

In this example, a bounded queue with capacity two demonstrates how `offer()` returns `true` when adding elements within capacity and `false` when the queue is full:

```java
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class PrintJobQueue {
public static void main(String[] args) {
Queue<String> printQueue = new ArrayBlockingQueue<>(2); // capacity of 2

boolean added = printQueue.offer("Document1");
System.out.println("Added Document1: " + added);

added = printQueue.offer("Document2");
System.out.println("Added Document2: " + added);

// Attempt to add another job to a full queue
added = printQueue.offer("Document3");
System.out.println("Added Document3: " + added);
}
}
```

The output generated by this code is:

```shell
Added Document1: true
Added Document2: true
Added Document3: false
```