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 loop. But 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 a boolean Variable
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()) {
if (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.
As always, the complete code samples for this article can be found over on GitHub.
Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses
Email:
public1989two@gmail.com
www.itsec.hk
www.itsec.vip
www.itseceu.uk
Leave a Reply