Skip to content

feature: #85 | Added try with resources capability#111

Merged
ShivamNagpal merged 1 commit intoZeplinko:developfrom
a-anand-91119:main
Mar 28, 2026
Merged

feature: #85 | Added try with resources capability#111
ShivamNagpal merged 1 commit intoZeplinko:developfrom
a-anand-91119:main

Conversation

@a-anand-91119
Copy link
Copy Markdown
Contributor

@a-anand-91119 a-anand-91119 commented Jan 4, 2026

New Methods (all marked @Preview)

Method Description
Try.run(ThrowingRunnable) Execute void actions that may throw checked exceptions
Try.withResources(ThrowingSupplier<R>, ThrowingFunction<R,T>) Single resource try-with-resources returning a value
Try.withResources(ThrowingSupplier<R1>, ThrowingSupplier<R2>, ThrowingBiFunction<R1,R2,T>) Two resource try-with-resources returning a value
Try.consumeResource(ThrowingSupplier<R>, ThrowingConsumer<R>) Single resource try-with-resources for void operations

Usage Examples

// Execute void action
Try<Empty> result = Try.run(() -> database.update());

// Single resource with return value
Try<String> content = Try.withResources(
    () -> new FileInputStream("data.txt"),
    is -> new String(is.readAllBytes())
);

// Two resources
Try<Long> copied = Try.withResources(
    () -> new FileInputStream("in.txt"),
    () -> new FileOutputStream("out.txt"),
    (in, out) -> in.transferTo(out)
);

// Void operation on resource
Try<Empty> written = Try.consumeResource(
    () -> new FileOutputStream("log.txt"),
    os -> os.write("Hello".getBytes())
);

Summary by CodeRabbit

  • New Features

    • Added functional exception-handling and resource-management helpers to the Try utility for cleaner execution of throwing operations and automatic resource cleanup.
  • Tests

    • Expanded unit tests to cover the new exception-handling and resource-management behaviors, including success, failure, and interruption scenarios.
  • Chores

    • Updated repository ignore list to include .DS_Store and a new .agent entry.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jan 4, 2026

📝 Walkthrough

Walkthrough

Adds new Try helpers for executing throwables and managing one- or two AutoCloseable resources (including a consumer variant), plus comprehensive unit tests for these helpers. Also updates the macOS section of .gitignore to re-add .DS_Store and add .agent.

Changes

Cohort / File(s) Summary
Configuration
\.gitignore
Re-added \.DS_Store and added \.agent in the macOS section.
API — Try utilities
src/main/java/.../Try.java
Added static helpers: run(ThrowingRunnable), withResources(ThrowingSupplier<R>, ThrowingFunction<? super R,? extends T>), withResources(ThrowingSupplier<R1>, ThrowingSupplier<R2>, ThrowingBiFunction<? super R1,? super R2,? extends T>), and consumeResource(ThrowingSupplier<R>, ThrowingConsumer<? super R>). Methods perform null checks, use try-with-resources, handle InterruptedException by re-interrupting the thread, and map other exceptions to Try.failure. Also added imports for throwing functional interfaces.
Tests
src/test/java/.../TryTest.java
Added extensive unit tests covering success/failure flows, null-argument validation, resource closure semantics (via a TestResource), interruption handling, and both single- and two-resource variants.

Sequence Diagram(s)

sequenceDiagram
  %%{init: {"themeVariables": {"actorBackground":"#E8F6EF","actorBorder":"#2E8B57","noteBackground":"#FFF8E1"}}}%%
  participant Caller as Caller
  participant TryUtil as Try
  participant R1 as Resource1
  participant R2 as Resource2
  participant Action as Action

  Caller->>TryUtil: withResources(resourceSupplier1, resourceSupplier2, action)
  alt open resources
    TryUtil->>R1: resourceSupplier1.get()
    Note right of R1: R1 opened
    TryUtil->>R2: resourceSupplier2.get()
    Note right of R2: R2 opened
    TryUtil->>Action: action.apply(R1, R2)
    Action-->>TryUtil: result / throws
  end
  alt success
    TryUtil-->>Caller: Try.success(result)
  else exception
    TryUtil-->>Caller: Try.failure(exception)
  end
  par close resources
    R2-->>TryUtil: close()
    R1-->>TryUtil: close()
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰
I nibbled code, then wrapped it tight,
Closed my resources through the night.
No leaks, no panic, just tidy cheer—
A rabbit's hug for Try is here! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.63% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly describes the main change: adding try-with-resources capability to the Try API, which matches the primary objective and code changes.
✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between adb29e0 and a10519e.

📒 Files selected for processing (3)
  • .gitignore
  • src/main/java/org/zeplinko/commons/lang/ext/core/Try.java
  • src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • .gitignore
🧰 Additional context used
🧬 Code graph analysis (1)
src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java (1)
src/main/java/org/zeplinko/commons/lang/ext/core/Try.java (1)
  • Try (80-753)
🔇 Additional comments (10)
src/main/java/org/zeplinko/commons/lang/ext/core/Try.java (5)

5-9: LGTM! Appropriate imports for the new API.

The new functional interface imports support the try-with-resources helper methods being added.


132-150: LGTM! Solid implementation of the run helper.

The method correctly handles void operations that may throw checked exceptions, following the established pattern from the to method. InterruptedException handling properly restores the thread's interrupt status.


152-177: LGTM! Well-designed single-resource helper.

The method properly encapsulates try-with-resources semantics, ensuring the resource is closed even when exceptions occur. The variance annotations provide good API flexibility.


179-218: LGTM! Robust two-resource helper with excellent documentation.

The nested try-with-resources correctly manages both resources, and the javadoc clearly explains the closure order and suppressed exception behavior.


220-245: LGTM! Clean implementation for resource-consuming side effects.

The method appropriately uses Try<Empty> for void operations and maintains consistency with the other new helpers.

src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java (5)

1191-1234: LGTM! Comprehensive test coverage for Try.run.

The tests verify all critical scenarios including null checks, success paths, exception handling, and proper InterruptedException behavior with thread interrupt flag management.


1236-1316: LGTM! Thorough testing of single-resource try-with-resources.

The tests comprehensively verify resource management, including the critical case that resources are closed even when exceptions occur. The TestResource helper effectively validates closure behavior.


1318-1439: LGTM! Excellent coverage of two-resource scenarios.

The tests meticulously verify resource management across all failure modes, including the important cases where resource acquisition fails at different stages. The verification that the first resource is closed when the second supplier fails demonstrates attention to edge cases.


1441-1528: LGTM! Complete test coverage for consumeResource.

The tests verify all necessary scenarios for resource-consuming operations, including side effect execution and proper resource cleanup across all code paths.


1530-1541: LGTM! Simple and effective test helper.

The TestResource class provides a clean way to verify that resources are properly closed during tests.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented Jan 4, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/main/java/org/zeplinko/commons/lang/ext/core/Try.java (1)

179-213: Consider documenting resource closure order.

The implementation correctly manages two resources using try-with-resources. The resources will be closed in reverse order of their acquisition (r2, then r1), which is the standard Java behavior.

Consider adding a note in the JavaDoc about the closure order to help users understand cleanup semantics, especially if they have resources with dependencies.

📝 Optional JavaDoc enhancement
     /**
      * Executes a block of code with two resources that are automatically closed,
      * capturing any exceptions into a {@code Try}.
+     * <p>
+     * Resources are closed in reverse order of acquisition: the second resource is
+     * closed first, followed by the first resource. If closing a resource throws an
+     * exception, it is added as a suppressed exception if the action also threw.
+     * </p>
      *
      * @param resourceSupplier1 A supplier that creates the first resource.
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f2970a5 and adb29e0.

📒 Files selected for processing (3)
  • .gitignore
  • src/main/java/org/zeplinko/commons/lang/ext/core/Try.java
  • src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java
🧰 Additional context used
🧬 Code graph analysis (1)
src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java (1)
src/main/java/org/zeplinko/commons/lang/ext/core/Try.java (1)
  • Try (80-748)
🔇 Additional comments (10)
.gitignore (1)

39-40: LGTM!

The macOS-specific ignores are appropriate. .DS_Store is standard for macOS directory metadata, and .agent appears to be a project-specific file.

src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java (5)

1191-1234: LGTM! Comprehensive test coverage for Try.run().

The tests properly verify:

  • Null parameter validation
  • Successful execution returning Empty
  • Exception propagation
  • InterruptedException handling with thread interrupt flag restoration and cleanup

1256-1316: LGTM! Thorough test coverage for single-resource withResources.

The tests verify all critical paths:

  • Resource closure on success
  • Exception handling when supplier fails (resource not created)
  • Exception handling when action fails (resource properly closed)
  • InterruptedException handling with proper thread state management

1348-1439: LGTM! Excellent test coverage for two-resource withResources.

The tests verify proper resource management:

  • Both resources closed on success
  • First resource closed when second supplier fails
  • Both resources closed when action fails
  • Proper InterruptedException handling

The resource closure order testing is particularly valuable for ensuring try-with-resources semantics are maintained.


1462-1528: LGTM! Complete test coverage for consumeResource.

The tests verify:

  • Successful side-effect execution with resource closure
  • Exception handling in both supplier and action
  • Proper InterruptedException handling with thread state restoration

1530-1541: LGTM! Simple and effective test helper.

The TestResource class provides a clean way to verify resource closure semantics without unnecessary complexity.

src/main/java/org/zeplinko/commons/lang/ext/core/Try.java (4)

5-9: LGTM! Necessary imports for the new API.

The throwing functional interface imports support the new resource management methods.


132-150: LGTM! Clean implementation of run() method.

The implementation correctly:

  • Validates the runnable parameter
  • Executes the runnable and captures exceptions
  • Restores the thread interrupt flag on InterruptedException
  • Returns Try<Empty> for void operations

The pattern is consistent with the existing to() method.


152-177: LGTM! Proper single-resource management implementation.

The method correctly uses try-with-resources to ensure the resource is closed regardless of whether the action succeeds or fails. The InterruptedException handling follows best practices by restoring the thread's interrupt status.


215-240: LGTM! Proper void-operation resource management.

The consumeResource method appropriately handles side-effect operations that don't return a value, following the same error handling and resource cleanup patterns as the other methods.

@ShivamNagpal
Copy link
Copy Markdown
Contributor

@codex review

1 similar comment
@ShivamNagpal
Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector
Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@ShivamNagpal
Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector
Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@ShivamNagpal
Copy link
Copy Markdown
Contributor

@codex review

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a10519e0b8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/main/java/org/zeplinko/commons/lang/ext/core/Try.java
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds new @Preview APIs to Try to support void execution and try-with-resources-style resource management while capturing exceptions into Try, along with unit tests and ignore-list updates.

Changes:

  • Added Try.run(...), Try.withResources(...) (1- and 2-resource variants), and Try.consumeResource(...) helper methods.
  • Added comprehensive unit tests for the new APIs, including interruption handling and resource closing behavior.
  • Updated .gitignore to ignore .DS_Store and .agent.

Reviewed changes

Copilot reviewed 2 out of 3 changed files in this pull request and generated 4 comments.

File Description
src/main/java/org/zeplinko/commons/lang/ext/core/Try.java Introduces new @Preview helper methods for throwing runnables and try-with-resources patterns returning Try.
src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java Adds test coverage for success/failure paths, null-argument behavior, resource closing, and InterruptedException handling.
.gitignore Adds .agent and normalizes .DS_Store entry.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java
Comment thread src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java
Comment thread src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java
Comment thread src/test/java/org/zeplinko/commons/lang/ext/core/TryTest.java
@ShivamNagpal ShivamNagpal merged commit 7959b57 into Zeplinko:develop Mar 28, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants