Skip to content

Codes #161

@siddharthrgade21-a11y

Description

@siddharthrgade21-a11y

import java.util.concurrent.*;
import java.math.BigInteger;

public class AdvancedConcurrency {

public static BigInteger calculateFactorial(int n) {
    BigInteger result = BigInteger.ONE;
    for (int i = 1; i <= n; i++) {
        result = result.multiply(BigInteger.valueOf(i));
    }
    return result;
}

public static void main(String[] args) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    // Submitting a Callable task to the executor
    Future<BigInteger> futureResult = executor.submit(() -> {
        System.out.println("Calculation started in a separate thread...");
        BigInteger factorial = calculateFactorial(50); // A moderately large number
        Thread.sleep(1000); // Simulate some delay
        return factorial;
    });

    // Main thread continues execution
    System.out.println("Main thread is doing other work...");

    try {
        // Get the result from the Future (this call blocks until the result is ready)
        BigInteger result = futureResult.get();
        System.out.println("Result received: " + result.toString().substring(0, 50) + "...");
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    } finally {
        executor.shutdown(); // Always shut down the executor
    }
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions