Sunday, January 12, 2025
HomeProgrammingJava Future Example

Java Future Example

In Java, a Future represents the result of an asynchronous computation. It allows you to retrieve the result of a task that is executed in the background, enabling parallel processing without blocking the main thread. Here’s a simple example of using Future with ExecutorService to perform a task asynchronously:

java

import java.util.concurrent.*;

public class FutureExample {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ExecutorService executor = Executors.newSingleThreadExecutor();

        // Submit a callable task

        Future<Integer> future = executor.submit(() -> {

            // Simulate a long-running task

            Thread.sleep(2000);

return 42;

        });

        // Do something else while the task is running

        System.out.println(“Task is running in the background…”);

        // Retrieve the result of the task

        Integer result = future.get();  // This will block until the result is available

        System.out.println(“Task completed. Result: ” + result);

        executor.shutdown();

    }

}

In this example, the task runs in the background while the main thread continues with other tasks. The future.get()method waits for the task to complete and retrieves the result. If the task is still running, it will block until the result is available.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x