CompletableFuture এবং Exception Handling

CompletableFuture (কমপ্লিটেবল ফিউচার) - জাভা (Java 8) - Computer Programming

376

Java 8 থেকে CompletableFuture একটি অত্যন্ত শক্তিশালী ক্লাস হিসেবে যুক্ত হয়েছে, যা asynchronous programming-এর জন্য ব্যবহৃত হয়। CompletableFuture হ'ল Future এর একটি উন্নত সংস্করণ, যা আপনাকে একাধিক থ্রেডে কাজ করে এবং ভবিষ্যতে কোনো মান (value) প্রাপ্তির জন্য অপেক্ষা করতে সাহায্য করে। এটি Java 8 এর java.util.concurrent প্যাকেজে অন্তর্ভুক্ত।

একটি গুরুত্বপূর্ণ দিক হল exception handling-এর মাধ্যমে CompletableFuture তে asynchronous কাজের ফলাফল প্রাপ্তির সময় exception বা error সঠিকভাবে হ্যান্ডল করা। এই ফিচারটি অ্যাসিঙ্ক্রোনাস প্রসেসে error recovery সহজ করে।

CompletableFuture এর মাধ্যমে Asynchronous Programming

CompletableFuture হল Future এর একটি উন্নত সংস্করণ, যা CompletableFuture.complete() মেথড ব্যবহার করে আপনার অ্যাসিঙ্ক্রোনাস কাজগুলিকে সমাপ্ত করতে সাহায্য করে এবং একটি ফলাফল বা exception প্রাপ্তি নির্ধারণ করে।


১. CompletableFuture এর মূল ব্যবহার

CompletableFuture সাধারণত supplyAsync(), runAsync() এবং thenApply(), thenAccept(), thenRun() ইত্যাদি মেথড ব্যবহার করে কাজ করে।

উদাহরণ: CompletableFuture basic example

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        // supplyAsync() ব্যবহার করে অ্যাসিঙ্ক্রোনাস কাজ
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            return 5 * 5; // 25 হবে
        });

        // thenApply() ব্যবহার করে ফলাফল প্রক্রিয়া করা
        future.thenApply(result -> {
            return result + 10;  // 25 + 10 = 35
        }).thenAccept(result -> {
            System.out.println("Final Result: " + result); // Output: Final Result: 35
        });
    }
}

এখানে, supplyAsync() একটি অ্যাসিঙ্ক্রোনাস কাজ চালায় এবং thenApply() এবং thenAccept() মেথডগুলির মাধ্যমে সেই কাজের ফলাফল প্রক্রিয়া করা হয়েছে।


২. Exception Handling with CompletableFuture

Java 8 এর CompletableFuture exception handling এর জন্য exceptionally(), handle() এবং whenComplete() মেথড প্রদান করেছে, যা অ্যাসিঙ্ক্রোনাস কাজের সময় exceptions হ্যান্ডেল করতে সহায়ক।

exceptionally():

exceptionally() মেথডটি exception ঘটলে একটি fallback (ডিফল্ট) মান প্রদান করে।

handle():

handle() মেথডটি success এবং failure উভয় ক্ষেত্রেই ব্যবহৃত হয় এবং এটি একটি BiFunction নেয় যা result এবং exception উভয়ই গ্রহণ করতে পারে।

whenComplete():

whenComplete() মেথডটি কাজ শেষ হওয়ার পরে, সফল বা ব্যর্থ হওয়ার পর কলব্যাক হিসেবে ব্যবহৃত হয়, কিন্তু এটি exception হ্যান্ডলিং করে না।


৩. Exception Handling Example

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExceptionHandling {
    public static void main(String[] args) {
        // একটি CompletableFuture তৈরি করা
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            if (true) {
                throw new RuntimeException("Something went wrong!");
            }
            return 50;
        });

        // exceptionally() দিয়ে exception handle করা
        future = future.exceptionally(ex -> {
            System.out.println("Exception caught: " + ex.getMessage());
            return 0; // fallback value
        });

        // ফলাফল প্রাপ্তি
        try {
            System.out.println("Final Result: " + future.get()); // Output: Exception caught: Something went wrong! Final Result: 0
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

এখানে exceptionally() ব্যবহার করা হয়েছে, যা exception ঘটলে একটি fallback মান প্রদান করেছে। যদি কোনও exception ঘটত, তবে 0 মানটি ফলস্বরূপ প্রাপ্ত হত।


৪. handle() Method for Exception Handling

handle() মেথডটি success এবং failure উভয় ক্ষেত্রেই কাজ করে এবং এটি একটি BiFunction নেয় যা একটি সফল ফলাফল অথবা exception গ্রহণ করতে পারে। এটি একটি Optional ফলাফল প্রদান করে, যাতে exception উপস্থিত থাকলে সেটি মোকাবেলা করা যায়।

উদাহরণ: handle() Exception Handling

import java.util.concurrent.CompletableFuture;

public class CompletableFutureHandleExample {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            if (true) {
                throw new RuntimeException("Error occurred!");
            }
            return 100;
        });

        // handle() মেথড ব্যবহার করে exception এবং result একসাথে handle করা
        future.handle((result, ex) -> {
            if (ex != null) {
                System.out.println("Exception handled: " + ex.getMessage());
                return 0; // return fallback value
            } else {
                return result;
            }
        }).thenAccept(result -> {
            System.out.println("Result: " + result);  // Output: Exception handled: Error occurred! Result: 0
        });
    }
}

এখানে, handle() মেথড ব্যবহার করা হয়েছে, যা exception এর ক্ষেত্রে fallback ভ্যালু প্রদান করেছে এবং সফলভাবে প্রাপ্ত ফলাফলটি প্রিন্ট করেছে।


৫. whenComplete() Method for Exception Handling

whenComplete() মেথডটি success এবং failure উভয় ক্ষেত্রেই কলব্যাক হিসেবে কাজ করে, তবে এটি exception হ্যান্ডলিং করে না। এটি BiConsumer ইনটারফেস গ্রহণ করে, যেখানে আপনি কাজের ফলাফল এবং exception প্রক্রিয়া করতে পারেন।

উদাহরণ: whenComplete() Exception Handling

import java.util.concurrent.CompletableFuture;

public class CompletableFutureWhenCompleteExample {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            if (true) {
                throw new RuntimeException("Error occurred!");
            }
            return 50;
        });

        // whenComplete() ব্যবহার করে exception এবং result উভয়ই প্রক্রিয়া করা
        future.whenComplete((result, ex) -> {
            if (ex != null) {
                System.out.println("Exception: " + ex.getMessage());
            } else {
                System.out.println("Result: " + result);
            }
        }).join(); // join() ব্যবহার করে asynchronous কাজের ফলাফল পাওয়া
    }
}

এখানে whenComplete() মেথডটি সফলভাবে কাজ শেষ হলে ফলাফল এবং exception উভয়ই প্রসেস করে।


৬. get() এবং join() মেথড

  • get() মেথডটি InterruptedException বা ExecutionException ছুড়ে দেয় যদি কোনো exception ঘটে।
  • join() মেথডটি RuntimeException ছুড়ে দেয় যদি কোনো exception ঘটে।
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    return 50;
});

// get() মেথড ব্যবহার
try {
    System.out.println("Result using get: " + future.get());
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}

// join() মেথড ব্যবহার
System.out.println("Result using join: " + future.join());

সারসংক্ষেপ

  • CompletableFuture হল Java 8-এ আসা একটি শক্তিশালী ফিচার যা asynchronous programming এর জন্য ব্যবহৃত হয়।
  • exceptionally(), handle(), এবং whenComplete() মেথডের মাধ্যমে exception handling সহজ করা হয়েছে।
  • CompletableFuture অ্যাসিঙ্ক্রোনাস কাজের ফলস্বরূপ exception হ্যান্ডলিং, callback এবং ফলাফল প্রাপ্তির জন্য কার্যকরী উপায় প্রদান করে।
Content added By
Promotion

Are you sure to start over?

Loading...