eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

We know that it’s possible to stop execution after a certain time duration in Java. Sometimes, there may be scenarios where we want to stop the execution of further code under certain conditions. In this tutorial, we’ll explore different solutions to this problem.

2. Introduction to the Problem

Stopping the execution of further code can be useful in situations where we want to terminate a long-running process, interrupt a running Thread, or handle exceptional cases. This enhances control and flexibility in our program.

Stopping the execution of further code enables efficient resource utilization, allows proper error handling, and allows graceful handling of unexpected situations. This can be helpful in these areas:

  • Efficient CPU Utilization
  • Memory Management
  • File and I/O Resources
  • Power Management

An example could be running a Thread in the background. We know that creating and running a Thread is costly in computational terms. When we no longer need a background Thread, we should interrupt and stop it to save computational resources:

@Override
public void run() {
    while (!isInterrupted()) {
        if (isInterrupted()) {
            break;
        }
        // complex calculation
    }
}

3. Using the return Statement

Mathematically, the factorial of a non-negative integer n, denoted as n!, is the product of all positive integers from 1 up to n. The factorial function can be defined recursively:

n! = n * (n - 1)!
0! = 1

The calculateFactorial(n) method below calculates the product of all positive integers less or equal to n:

int calculateFactorial(int n) {
    if (n <= 1) {
        return 1; // base case
    }
    return n * calculateFactorial(n - 1);
}

Here, we use the return statement as the base case of this recursive function. If n is 1 or less, the function returns 1. But if n is greater than or equal to 2, the function calculates the factorial and returns the value.

Another example of a return statement could be downloading a file. If fileUrl and destinationPath are null or empty in the download() method, we stop executing further code:

void download(String fileUrl, String destinationPath) throws MalformedURLException {
    if (fileUrl == null || fileUrl.isEmpty() || destinationPath == null || destinationPath.isEmpty()) {
        return;
    }
    // execute downloading
    URL url = new URL(fileUrl);
    try (InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(destinationPath)) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

4. Using break Statements in Loops

To calculate the sum of an array, we can use a simple Java for loopBut when there is a negative value in the array the method stops calculating further values of the array, and the break statement terminates the loop. As a result, the control flow is redirected to the statement immediately following the end of the for loop:

int calculateSum(int[] x) {
    int sum = 0;
    for (int i = 0; i < 10; i++) {
        if (x[i] < 0) {
            break;
        }
        sum += x[i];
    }
    return sum;
}

To exit a particular iteration of a loop, we can use the break statement to exit out of the scope of the loop:

@Test
void givenArrayWithNegative_whenStopExecutionInLoopCalled_thenSumIsCalculatedIgnoringNegatives() {
    StopExecutionFurtherCode stopExecutionFurtherCode = new StopExecutionFurtherCode();
    int[] nums = { 1, 2, 3, -1, 1, 2, 3 };
    int sum = stopExecutionFurtherCode.calculateSum(nums);
    assertEquals(6, sum);
}

5. Using a break Statement in Labeled Loops

A labeled break terminates the outer loop. Once the outer loop completes its iterations, the program’s execution naturally moves to the subsequent statement.

Here, the processLines() method takes an array of String and prints the line. However, when the program encounters a stop in the array, it discontinues printing the line and exits the labeled loop’s scope using the break statement:

int processLines(String[] lines) {
    int statusCode = 0;
    parser:
    for (String line : lines) {
        System.out.println("Processing line: " + line);
        if (line.equals("stop")) {
            System.out.println("Stopping parsing...");
            statusCode = -1;
            break parser; // Stop parsing and exit the loop
        }
        System.out.println("Line processed.");
    }
    return statusCode;
}

6. Using System.exit()

To stop the execution of further code, we can use a flag variable. System.exit(0) is commonly used to terminate the currently running Java program with an exit status of 0.

Here, we use conditional statements to determine whether the program should continue running or terminate:

public class StopExecutionFurtherCode {

    boolean shouldContinue = true;

    int performTask(int a, int b) {
        if (!shouldContinue) {
            System.exit(0);
        }
        return a + b;
    }

    void stop() {
        this.shouldContinue = false;
    }
}

We terminate the program using System.exit(0) before reaching the return statement if shouldContinue is false.

If the performTask() method is called with the arguments 10 and 20, and the shouldContinue state is false, the program halts its execution. Rather than giving the sum of the numbers, this method terminates the program:

StopExecutionFurtherCode stopExecution = new StopExecutionFurtherCode();
stopExecution.stop();
int performedTask = stopExecution.performTask(10, 20);

There are a lot of long-running tasks when doing batch processing. We can notify the operating system about the status after finishing batch processing. When we use System.exit(statusCode), the operating system can determine whether the shutdown was normal or abnormal. We can use System.exit(0) for normal shutdowns and System.exit(1) for abnormal shutdowns.

7. Using an Exception

Exceptions are unexpected errors or abnormal conditions that applications face and need to be handled appropriately. It’s essential to know about errors and exceptions. In this example, we need generics to check the parameter type. If the parameter type is Number, we use an Exception to stop the execution of the method:

<T> T stopExecutionUsingException(T object) {
    if (object instanceof Number) {
        throw new IllegalArgumentException("Parameter can not be number.");
    }
    T upperCase = (T) String.valueOf(object).toUpperCase(Locale.ENGLISH);
    return upperCase;
}

Here, we see that whenever we pass a Number as a parameter, it throws an Exception. On the other hand, if we pass String as the input parameter, it returns the uppercase of the given String:

@Test
void givenName_whenStopExecutionUsingExceptionCalled_thenNameIsConvertedToUpper() {
    StopExecutionFurtherCode stopExecutionFurtherCode = new StopExecutionFurtherCode();
    String name = "John";
    String result1 = stopExecutionFurtherCode.stopExecutionUsingException(name);
    assertEquals("JOHN", result1);
    try {
        Integer number1 = 10;
        assertThrows(IllegalArgumentException.class, () -> {
            int result = stopExecutionFurtherCode.stopExecutionUsingException(number1);
        });
    } catch (Exception e) {
        Assert.fail("Unexpected exception thrown: " + e.getMessage());
    }
}

In this example, we used the basics of Java generics. Generics are useful for type safety, compile-time type checking, collection framework, etc.

8. Using the interrupt() Method in Thread

Let’s create a class called InterruptThread to use the interrupt() method in a running thread.

When a thread is interrupted, it sets the interrupt flag of the thread, indicating that it has been requested to stop. If the thread gets an interrupt signal, it stops the while loop scope in the program:

class InterruptThread extends Thread {
    @Override
    public void run() {
        while (!isInterrupted()) {
            break;
            // business logic
        }
    }
}

We need to start a thread using the start() method and pause the program for 2000ms. Then using the interrupt() signal stops the execution in the while loop and stops the thread:

@Test
void givenThreadRunning_whenInterruptCalled_thenThreadExecutionIsStopped() throws InterruptedException {
    InterruptThread stopExecution = new InterruptThread();
    stopExecution.start();
    Thread.sleep(2000);
    stopExecution.interrupt();
    stopExecution.join();
    assertTrue(!stopExecution.isAlive());
}

9. Conclusion

In this article, we’ve explored multiple programmatic ways to stop the execution of further code in Java programs. To halt a program, we can use System.exit(0) for immediate termination. Alternatively, return and break statements help to exit particular methods or loops, while exceptions allow for the interruption of code execution.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments