Thuta Learning
Java
AdvancedProgrammingအခြေခံ

Concurrency & Virtual Threads

Javaသင်ခန်းစာ 3040 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Platform thread နဲ့ virtual thread ကွာခြားချက်နဲ့ virtual thread ဘယ်အလုပ်အတွက် သင့်တော်လဲ ရှင်းပြနိုင်ဖို့
  • Executors.newVirtualThreadPerTaskExecutor() ကို try-with-resources နဲ့ သုံးပြီး task တစ်ခုစီကို thread တစ်ခုစီနဲ့ run နိုင်ဖို့
  • Future.get() နဲ့ ရလဒ်ကို စုပြီး ExecutionException ကနေ task ရဲ့ failure ကို ထုတ်ယူနိုင်ဖို့
  • Shared counter ကို AtomicInteger နဲ့ ကာကွယ်ပြီး race condition ကို ရှောင်နိုင်ဖို့
  • Thread တွေကြားက output အစဉ်ကို deterministic ဖြစ်အောင် ပြုလုပ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

စားသောက်ဆိုင်တစ်ဆိုင်မှာ စားပွဲထိုး တစ်ယောက်တည်းရှိပြီး မီးဖိုချောင်က ဟင်းကို ရပ်စောင့်နေရင် ကျန်တဲ့ စားပွဲတွေ အားလုံး စောင့်ရပါတယ်။ Thread ဆိုတာ စားပွဲထိုး တစ်ယောက်လိုပါပဲ — thread အများရှိရင် အလုပ်တွေကို တစ်ပြိုင်နက် လုပ်လို့ ရပါတယ်။ ဒါပေမယ့် ရိုးရိုး (platform) thread တွေက လစာကြီးတဲ့ ဝန်ထမ်းတွေလို ဈေးကြီးလို့ ထောင်ချီ ငှားလို့ မရပါဘူး။

Virtual thread တွေကတော့ ဟင်းစောင့်နေတုန်း ကောင်တာမှာ ထိုင်ခုံကို ပြန်ပေးလိုက်တဲ့ စားပွဲထိုးလိုပါ — ထိုင်ခုံ (CPU core) နည်းနည်းနဲ့ စားပွဲထိုး ထောင်ချီကို ဆောင်ရွက်စေနိုင်ပါတယ်။ စောင့်ရတဲ့ အလုပ် (network, database, file) များတဲ့ program တွေအတွက် အထူးသင့်တော်ပါတယ်။

Problem → Why → Solution

ပြဿနာ: thread တွေက counter တစ်ခုကို ဝိုင်းပြင်တဲ့အခါ

အောက်က program က thread ၁၀,၀၀၀ ကို စတင်ပြီး တစ်ခုစီက count++ လုပ်ပါတယ်။ ရလဒ်က 10000 ဖြစ်သင့်ပေမယ့် 9,8xx လို ပိုနည်းတဲ့ နံပါတ် ထွက်လာနိုင်ပါတယ် (အမြဲ ဖြစ်တာ မဟုတ်လို့ ပိုအန္တရာယ်ရှိပါတယ်)။ count++ က တစ်ဆင့်တည်း မဟုတ်ဘဲ "ဖတ်၊ ၁ ပေါင်း၊ ပြန်ရေး" ဆိုတဲ့ အဆင့်သုံးဆင့်ဖြစ်လို့ thread နှစ်ခုက တန်ဖိုးတူတူကို ဖတ်ပြီး တစ်ယောက်ရဲ့ update ကို တစ်ယောက်က ဖုံးပစ်ပါတယ်။

ဒီ program မှာ ဒုတိယ bug လည်း ရှိပါတယ် — main() က thread တွေ ပြီးအောင် မစောင့်ဘဲ count ကို print ထုတ်လို့ thread တချို့ မပြီးသေးခင် ဖတ်မိနိုင်ပါတယ်။

Main.java
public class Main {
  static int count = 0;

  public static void main(String[] args) {
    for (int i = 0; i < 10_000; i++) {
      Thread.ofVirtual().start(() -> count++);   // read-add-write race
    }
    System.out.println(count);   // no join: threads may still be running
  }
}

ဘာကြောင့် ဒီလို ဖြစ်တာလဲ

Thread တွေကို scheduler က ဘယ်အချိန် run မလဲ၊ ဘယ်အချိန် ရပ်မလဲ ဆုံးဖြတ်ပြီး ကိုယ်က ထိန်းချုပ်လို့ မရပါဘူး။ Thread အများက mutable data တစ်ခုတည်းကို synchronization မပါဘဲ ပြင်ရင် ရလဒ်က timing ပေါ် မူတည်သွားပါတယ်၊ ဒါကို race condition လို့ ခေါ်ပါတယ်။ ဖြေရှင်းချက်က shared state ကို AtomicInteger, lock ဒါမှမဟုတ် concurrent collection နဲ့ ကာကွယ်တာ ဒါမှမဟုတ် လုံးဝ မမျှဝေဘဲ task တစ်ခုစီက ရလဒ်ကို return ပြန်ပြီး တစ်နေရာတည်းမှာ စုတာ၊ ပြီးတော့ ရလဒ်ကို မဖတ်ခင် thread အားလုံးကို join ဒါမှမဟုတ် Future.get() နဲ့ စောင့်တာပါ။

Core concept: platform thread နဲ့ virtual thread

Java ရဲ့ ရိုးရိုး thread (platform thread) တစ်ခုစီက operating system thread တစ်ခုနဲ့ တစ်ခုချင်း တွဲထားပြီး stack အတွက် memory အများကြီး ကြိုယူထားပါတယ်။ ဒါကြောင့် thread ထောင်ချီ ဖန်တီးရင် memory နဲ့ context switch ကုန်ကျစရိတ် ကြီးလာပြီး server တွေက thread pool အသေးလေးတစ်ခုကို မျှသုံးရပါတယ်။ Request တစ်ခုက database ကို စောင့်နေတုန်း သူ့ thread က ဘာမှ မလုပ်ဘဲ ပိတ်ဆို့နေလို့ pool ပြည့်သွားရင် request အသစ်တွေ တန်းစီစောင့်ရပါတယ်။

Virtual thread တွေ (Java 21 မှာ JEP 444 နဲ့ final ဖြစ်လာပါတယ်) ကို JVM က ကိုယ်တိုင် စီမံပါတယ်။ Virtual thread တစ်ခုက run တဲ့အခါ carrier လို့ခေါ်တဲ့ platform thread အနည်းငယ်ထဲက တစ်ခုပေါ် mount လုပ်ပြီး Thread.sleep(), socket I/O လို blocking operation မှာ unmount လုပ်ကာ carrier ကို တခြား virtual thread အတွက် ပြန်လွှတ်ပေးပါတယ်။ ဒါကြောင့် virtual thread ကို ဈေးပေါပေါနဲ့ ထောင်ချီ သိန်းချီ ဖန်တီးနိုင်ပြီး task တစ်ခုကို thread တစ်ခုပေးတဲ့ ရိုးရှင်းတဲ့ blocking style code ကို ဆက်ရေးနိုင်ပါတယ်။

Virtual thread က code ကို ပိုမြန်အောင် မလုပ်ပါဘူး — စောင့်ရတဲ့ အလုပ်တွေကို တစ်ပြိုင်နက် ပိုများများ လုပ်နိုင်အောင်ပဲ လုပ်ပေးတာပါ။ CPU ကို အပြည့်သုံးတဲ့ တွက်ချက်မှုတွေမှာ core အရေအတွက်ထက် ပိုမြန်မလာပါဘူး။ Virtual thread တွေကို pool မလုပ်ရပါဘူး၊ task အသစ်တိုင်းအတွက် အသစ်ဖန်တီးပါ။ Database လို resource တစ်ခုကို တစ်ပြိုင်နက် ခေါ်တဲ့ အရေအတွက်ကို ကန့်သတ်ချင်ရင် Semaphore ကို သုံးပါ။

Race condition တွေကတော့ virtual thread မှာလည်း platform thread မှာလိုပဲ ဖြစ်ပါတယ်၊ ဒါကြောင့် shared state ကို ကာကွယ်ဖို့ လိုဆဲပါ။ Java 21 မှာ synchronized block ထဲမှာ block ဖြစ်ရင် virtual thread က carrier ကို ကိုင်ထားဆဲ (pinned) ဖြစ်လို့ အကြာကြီး စောင့်ရတဲ့ နေရာတွေမှာ ReentrantLock ကို ပိုသင့်တော်ပါတယ်။ နောက်ပိုင်း JDK version တွေမှာ ဒီကန့်သတ်ချက်ကို လျှော့ချထားလို့ ကိုယ်သုံးတဲ့ version ရဲ့ release notes ကို စစ်ပါ။

မှတ်ထားရမယ့် ပုံစံ: submit → စောင့် → အစဉ်လိုက် စု
  1. Task တစ်ခုကို virtual thread တစ်ခု
  2. Block ဖြစ်ရင် carrier ကို ပြန်လွှတ်
  3. Future ကို submit အစဉ်နဲ့ သိမ်း
  4. get() နဲ့ ရလဒ်/failure ကို စု
  5. Executor ကို close လုပ်ပြီး စောင့်

Thread တွေ ပြီးတဲ့ အစဉ်က ကျပန်းပါ၊ ကိုယ်သိမ်းထားတဲ့ Future အစဉ်ကပဲ output အစဉ်ကို ဆုံးဖြတ်ရပါမယ်။

အထွေထွေ ပုံစံ

java
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
  List<Future<Result>> futures = new ArrayList<>();
  for (Input input : inputs) {
    futures.add(executor.submit(() -> blockingWork(input)));
  }
  for (Future<Result> f : futures) {
    use(f.get());              // throws ExecutionException if the task failed
  }
}                              // close() waits for every submitted task

Thread t = Thread.ofVirtual().start(() -> work());
t.join();

Virtual-thread-per-task executor ကို try-with-resources ထဲမှာ ဖန်တီးပြီး task တစ်ခုစီကို submit လုပ်ကာ Future တွေကို list ထဲ သိမ်းပါတယ်။ get() က ရလဒ်ကို စောင့်ယူပြီး task က exception ပစ်ခဲ့ရင် ExecutionException အဖြစ် ပြန်ပစ်ပါတယ်။ Executor တစ်ခုမလိုရင် Thread.ofVirtual().start() နဲ့ thread တစ်ခုတည်း စပြီး join() နဲ့ စောင့်လို့ ရပါတယ်။

Example: ဈေးနှုန်း သုံးခုကို တစ်ပြိုင်နက် ယူခြင်း

ဒီ example က network call ကို Thread.sleep(200) နဲ့ အတုလုပ်ထားတဲ့ task သုံးခုကို virtual thread တွေပေါ်မှာ တစ်ပြိုင်နက် run ပြီး task တစ်ခုစီက isVirtual() နဲ့ virtual thread ပေါ်မှာ run နေကြောင်း ပြန်ပြောပါတယ်။ Task တစ်ခုစီ 200 ms ကြာပေမယ့် တစ်ပြိုင်နက် စောင့်ကြလို့ စုစုပေါင်း 600 ms မဟုတ်ဘဲ 200 ms နားလောက်ပဲ ကြာပါတယ်။ Output ကို Future စာရင်းရဲ့ အစဉ်နဲ့ print ထုတ်လို့ run တိုင်း အတူတူ ထွက်ပါတယ်။

Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
  static String fetchPrice(String product) throws InterruptedException {
    Thread.sleep(200);                       // pretend this is a slow network call
    boolean virtual = Thread.currentThread().isVirtual();
    return product + " = " + product.length() * 10 + " (virtual: " + virtual + ")";
  }

  public static void main(String[] args) throws InterruptedException, ExecutionException {
    List<String> products = List.of("apple", "kiwi", "banana");
    List<Future<String>> futures = new ArrayList<>();

    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
      for (String product : products) {
        futures.add(executor.submit(() -> fetchPrice(product)));
      }
      for (Future<String> future : futures) {
        System.out.println(future.get());    // waits; prints in submission order
      }
    }
    System.out.println("All " + futures.size() + " tasks finished");
  }
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Line 10Thread.sleep(200); // pretend this is a slow network call

    Virtual thread က sleep ဖြစ်နေတုန်း carrier thread ကနေ unmount လုပ်လို့ carrier က တခြား task တွေကို ဆက် run နိုင်ပါတယ်။

  2. Line 19try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {

    Submit လုပ်တဲ့ task တိုင်းအတွက် virtual thread အသစ် ဖန်တီးတဲ့ executor ပါ။ Java 19 ကစပြီး ExecutorService က AutoCloseable ဖြစ်လို့ try-with-resources နဲ့ သုံးလို့ ရပါတယ်။

  3. Line 21futures.add(executor.submit(() -> fetchPrice(product)));

    submit() က task ကို ချက်ချင်း စတင်ပြီး Future ကို တန်းပြန်ပေးပါတယ်။ Lambda က exception ပစ်နိုင်ပြီး value ပြန်လို့ Callable<String> ဖြစ်ပါတယ်၊ for-each variable product က effectively final ဖြစ်လို့ lambda ထဲမှာ သုံးလို့ ရပါတယ်။

  4. Line 24System.out.println(future.get()); // waits; prints in submission order

    get() က အဲဒီ task ပြီးတဲ့အထိ စောင့်ပါတယ်။ Main thread တစ်ခုတည်းကပဲ list အစဉ်အတိုင်း print ထုတ်လို့ task တွေ ဘယ်အစဉ်နဲ့ ပြီးပြီး output က apple, kiwi, banana ပဲ ထွက်ပါတယ်။

  5. Line 26}

    try block ရဲ့ အဆုံးမှာ executor.close() ကို အလိုအလျောက် ခေါ်ပြီး submit လုပ်ထားတဲ့ task အားလုံး ပြီးတဲ့အထိ စောင့်ပါတယ်။ ဒါကြောင့် "All 3 tasks finished" က အမြဲ နောက်ဆုံးမှ ထွက်ပါတယ်။

You should see
apple = 50 (virtual: true)
kiwi = 40 (virtual: true)
banana = 60 (virtual: true)
All 3 tasks finished

Race condition ကို AtomicInteger နဲ့ ပြင်ခြင်း

Problem section က counter ကို AtomicInteger နဲ့ ပြင်ပြီး thread အားလုံးကို join() နဲ့ စောင့်လိုက်ရင် ရလဒ်က အမြဲ မှန်ပါတယ်။ incrementAndGet() က "ဖတ်၊ ပေါင်း၊ ရေး" ကို ခွဲလို့မရတဲ့ (atomic) operation တစ်ခုအဖြစ် လုပ်လို့ update တွေ မပျောက်တော့ပါဘူး။ Thread တွေထဲကနေ print မထုတ်ဘဲ အားလုံးပြီးမှ main thread ကနေ တစ်ကြိမ်တည်း print ထုတ်ထားတာကိုလည်း သတိထားပါ။

Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
  public static void main(String[] args) throws InterruptedException {
    AtomicInteger hits = new AtomicInteger();
    List<Thread> threads = new ArrayList<>();

    for (int i = 0; i < 1_000; i++) {
      Thread t = Thread.ofVirtual().start(() -> hits.incrementAndGet());
      threads.add(t);
    }
    for (Thread t : threads) {
      t.join();                              // wait for every thread
    }
    System.out.println("Hits: " + hits.get());
  }
}

Blocking task ၁၀,၀၀၀

အောက်က program က တစ်စက္ကန့်စီ sleep လုပ်တဲ့ task ၁၀,၀၀၀ ကို virtual thread တွေပေါ်မှာ run ပါတယ်။ Thread ၁၀ ခု pool နဲ့ဆိုရင် ၁၀၀၀ စက္ကန့်လောက် ကြာမယ့် အလုပ်ပါ။ Virtual thread တွေနဲ့တော့ အားလုံး တစ်ပြိုင်နက် စောင့်လို့ ပုံမှန်စက်မှာ စက္ကန့် အနည်းငယ်အတွင်း ပြီးပါတယ် — တိကျတဲ့ အချိန်က စက်ပေါ် မူတည်လို့ program က ၁၀ စက္ကန့်အောက်လား ဆိုတာပဲ print ထုတ်ပါတယ်။

Main.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
  public static void main(String[] args) {
    AtomicInteger done = new AtomicInteger();
    long start = System.nanoTime();

    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
      for (int i = 0; i < 10_000; i++) {
        executor.submit(() -> {
          Thread.sleep(1_000);               // 10,000 tasks blocking for 1 second
          return done.incrementAndGet();
        });
      }
    }                                        // close() waits for all of them

    long seconds = (System.nanoTime() - start) / 1_000_000_000;
    System.out.println("Completed: " + done.get());
    System.out.println("Took less than 10 s: " + (seconds < 10));
  }
}

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Web server တွေက request တစ်ခုကို thread တစ်ခုနဲ့ ကိုင်တွယ်တာ များပါတယ်။ Request တစ်ခုက database query, တခြား microservice ကို HTTP call, cache lookup တွေကို စောင့်ရင်း အချိန်အများစု ကုန်လို့ virtual thread တွေနဲ့ run ရင် thread pool ပြည့်လို့ တန်းစီရတာ လျော့ပါတယ်။ Spring Boot (3.2 နဲ့ နောက်ပိုင်း) မှာ spring.threads.virtual.enabled=true setting နဲ့ request handling ကို virtual thread ပေါ် ပြောင်းလို့ ရပါတယ် — အသေးစိတ်ကို ကိုယ်သုံးတဲ့ version ရဲ့ documentation မှာ စစ်ပါ။

Dashboard တစ်ခုအတွက် user profile, order history, recommendation ကို service သုံးခုဆီက တစ်ပြိုင်နက် ခေါ်ပြီး Future တွေနဲ့ စုတာ၊ batch job တစ်ခုက file ရာချီကို download လုပ်တာတွေမှာ ဒီ lesson ရဲ့ pattern ကို တိုက်ရိုက် သုံးပါတယ်။ ဒီလို system တွေမှာ external API ကို တစ်ပြိုင်နက် ခေါ်တဲ့ အရေအတွက်ကို Semaphore နဲ့ ကန့်သတ်ပြီး task တစ်ခုစီရဲ့ failure ကို ExecutionException ကနေ log ရေးကာ ကျန်တဲ့ ရလဒ်တွေနဲ့ ဆက်လုပ်ပါတယ်။ Java 21 မှာ preview feature အဖြစ်ပါတဲ့ structured concurrency (StructuredTaskScope) က task အုပ်စုတစ်ခုရဲ့ cancellation နဲ့ failure ကို ပိုရှင်းအောင် ကိုင်တွယ်ပေးဖို့ ရည်ရွယ်ပါတယ်၊ production မှာ မသုံးခင် status ကို release notes မှာ စစ်ပါ။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. Virtual thread တွေကို fixed pool ထဲ ထည့်တာ

Executors.newFixedThreadPool(10, Thread.ofVirtual().factory()) လို ရေးတာက platform thread လို ရှားပါးတယ်လို့ ထင်ပြီး ကန့်သတ်တာပါ၊ virtual thread ရဲ့ အကျိုးကျေးဇူး ပျောက်သွားပါတယ်။ Task တစ်ခုစီကို thread အသစ်ပေးပြီး resource ကို ကာကွယ်ဖို့ လိုရင် Semaphore နဲ့ ကန့်သတ်ပါ။

2. Thread-safe collection တစ်ခုက race အားလုံးကို ဖြေရှင်းတယ်လို့ ထင်တာ

ConcurrentHashMap ကို သုံးထားပေမယ့် if (!map.containsKey(k)) map.put(k, v); လို စစ်ပြီးမှ ထည့်တဲ့ အဆင့်နှစ်ဆင့်ကြားမှာ တခြား thread ဝင်လာနိုင်ပါတယ်။ Method တစ်ခုချင်းက thread-safe ဖြစ်ပေမယ့် ပေါင်းစပ်ထားတာက မဟုတ်ပါဘူး။ putIfAbsent(), computeIfAbsent(), merge() လို atomic method တွေကို သုံးပါ။

3. Thread တွေထဲကနေ တိုက်ရိုက် print ထုတ်တာ

Task တိုင်းက System.out.println() ကို ကိုယ်တိုင် ခေါ်ရင် output အစဉ်က run တိုင်း ပြောင်းပြီး log နဲ့ test တွေကို နားလည်ရ ခက်စေပါတယ်။ Task က ရလဒ်ကို return ပြန်ပြီး main thread က Future အစဉ်အတိုင်း print ထုတ်ပါ။

4. get() ရဲ့ ExecutionException ကို လျစ်လျူရှုတာ

Task ထဲက exception ကို Future.get() က ExecutionException နဲ့ ထုပ်ပြီး ပြန်ပစ်ပါတယ်။ get() ကို မခေါ်ရင် failure ကို ဘယ်တော့မှ မသိရပါဘူး။ e.getCause() နဲ့ အရင်းခံ exception ကို ယူပါ။

Mini challenge

Mini challenge: user profile တွေကို တစ်ပြိုင်နက် load လုပ်ခြင်း

User id လေးခုကို virtual thread တွေနဲ့ တစ်ပြိုင်နက် load လုပ်ပါ။ Id 3 က exception ပစ်ပြီး task တွေ ပြီးတဲ့ အစဉ်က id အစဉ်နဲ့ မတူပါဘူး။ Output ကို id အစဉ်အတိုင်း ထုတ်ပြီး failure ကို message နဲ့ ပြကာ အောင်မြင်တဲ့ အရေအတွက်ကို print ထုတ်ပါ။

  • newVirtualThreadPerTaskExecutor() ကို try-with-resources နဲ့ သုံးရမယ်
  • Future တွေကို id အစဉ်ကို ထိန်းထားတဲ့ LinkedHashMap<Integer, Future<String>> ထဲ သိမ်းရမယ်
  • ExecutionException ကို ဖမ်းပြီး getCause().getMessage() ကို ပြရမယ်
  • Task တွေထဲကနေ print မထုတ်ရ၊ output က run တိုင်း အတူတူ ဖြစ်ရမယ်
Main.java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
  static String loadUser(int id) throws InterruptedException {
    Thread.sleep(50L * (4 - id % 4));        // later ids finish first
    // TODO: throw IllegalStateException("user 3 not found") for id 3
    return "user-" + id;
  }

  public static void main(String[] args) throws InterruptedException {
    List<Integer> ids = List.of(1, 2, 3, 4);
    Map<Integer, Future<String>> futures = new LinkedHashMap<>();
    // TODO: submit loadUser(id) for every id on a virtual-thread executor
    // TODO: print "<id> -> <result>" or "<id> -> failed: <message>" in id order
    // TODO: print "Loaded <n> of <total>"
  }
}

ရလဒ်: Program က run တိုင်း ဒီ output ကို ထုတ်ရပါမယ်: 1 -> user-1 2 -> user-2 3 -> failed: user 3 not found 4 -> user-4 Loaded 3 of 4

အရိပ်အမြွက် ကြည့်ရန်

Task တွေကို try block ထဲမှာ submit လုပ်ပြီး try ပြီးမှ Future တွေကို loop ပတ်ပါ — close() က task အားလုံး ပြီးအောင် စောင့်ပြီးသားမို့ get() က ချက်ချင်း ပြန်လာပါတယ်။ ExecutionException ရဲ့ getCause() က task ပစ်ခဲ့တဲ့ IllegalStateException ပါ။

အဖြေ ကြည့်ရန်
Main.java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
  static String loadUser(int id) throws InterruptedException {
    Thread.sleep(50L * (4 - id % 4));        // later ids finish first
    if (id == 3) {
      throw new IllegalStateException("user " + id + " not found");
    }
    return "user-" + id;
  }

  public static void main(String[] args) throws InterruptedException {
    List<Integer> ids = List.of(1, 2, 3, 4);
    Map<Integer, Future<String>> futures = new LinkedHashMap<>();

    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
      for (int id : ids) {
        futures.put(id, executor.submit(() -> loadUser(id)));
      }
    }                                        // close() waits for every task

    int loaded = 0;
    for (Map.Entry<Integer, Future<String>> entry : futures.entrySet()) {
      try {
        System.out.println(entry.getKey() + " -> " + entry.getValue().get());
        loaded++;
      } catch (ExecutionException e) {
        System.out.println(entry.getKey() + " -> failed: " + e.getCause().getMessage());
      }
    }
    System.out.println("Loaded " + loaded + " of " + ids.size());
  }
}

Quick Quiz 1 / 3

ဘယ် workload က virtual thread ကနေ အကျိုးအများဆုံး ရမလဲ။

Quick Quiz 2 / 3

Future.get() ခေါ်တဲ့အခါ task က IllegalStateException ပစ်ခဲ့ရင် ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

Virtual thread ၁,၀၀၀ က static int total ကို total += 1 နဲ့ ပြင်ပြီး join() အားလုံး လုပ်ပြီးမှ print ထုတ်ရင် ဘာထွက်မလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Thread အများက mutable data ကို synchronization မပါဘဲ မျှပြင်ရင် race condition ဖြစ်လို့ AtomicInteger, lock ဒါမှမဟုတ် return value နဲ့ စုတာကို သုံးပါ။
  • Java 21 ရဲ့ virtual thread တွေက blocking ဖြစ်ရင် carrier ကို ပြန်လွှတ်လို့ I/O စောင့်ရတဲ့ task ထောင်ချီအတွက် ဈေးပေါပြီး CPU အလုပ်ကိုတော့ မမြန်စေပါဘူး။
  • newVirtualThreadPerTaskExecutor() ကို try-with-resources နဲ့ သုံးပါ၊ close() က task အားလုံးကို စောင့်ပါတယ်၊ virtual thread ကို pool မလုပ်ပါနဲ့။
  • Future.get() နဲ့ ရလဒ်နဲ့ ExecutionException ကို စုပြီး output ကို Future အစဉ်အတိုင်း main thread ကနေ ထုတ်ပါ။

JEP 444: Virtual Threads — OpenJDK

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Concurrency & Virtual Threads | Thuta Learning