1Go: Handler.Quote nhận request báo giá, tạo ctx bằng context.WithTimeout(r.Context(), 2*time.Second) rồi bọc tiếp bằng errgroup.WithContext. defer cancel() bảo đảm timer luôn được giải phóng.Go: Handler.Quote receives the quote request, creates ctx with context.WithTimeout(r.Context(), 2*time.Second) and wraps it with errgroup.WithContext. defer cancel() guarantees the timer is always released.
2Hai lần g.Go chạy stock task (h.stock.Available(ctx, id)) và shipping task (h.shipping.Fee(ctx, id)) với CÙNG ctx, nên cả hai chia nhau ngân sách 2 giây còn lại.Two g.Go calls run the stock task (h.stock.Available(ctx, id)) and the shipping task (h.shipping.Fee(ctx, id)) with the SAME ctx, so both share the remaining 2-second budget.
3ShippingClient.Fee dựng request bằng http.NewRequestWithContext(ctx, ...) rồi gọi c.http.Do(req) tới shipping.internal. Hãng vận chuyển chậm 30 giây nên shipping task đứng chờ.ShippingClient.Fee builds the request with http.NewRequestWithContext(ctx, ...) and calls c.http.Do(req) against shipping.internal. The carrier takes 30 seconds, so the shipping task waits.
4Đến mốc 2 giây, deadline huỷ ctx và kênh ctx.Done() bị đóng. Transport HTTP thấy tín hiệu, ngắt lời gọi; Fee trả lỗi đã bọc bằng %w.At 2 seconds the deadline cancels ctx and ctx.Done() is closed. The HTTP transport sees the signal and aborts the call; Fee returns an error wrapped with %w.
5g.Wait() chờ cả hai goroutine thoát rồi trả lỗi đầu tiên. errors.Is(err, context.DeadlineExceeded) đúng nên handler trả 504.g.Wait() waits for both goroutines to exit and returns the first error. errors.Is(err, context.DeadlineExceeded) is true, so the handler returns 504.
6Java làm cùng việc đó trong QuoteService.quote(orderId): mở scope = Executors.newVirtualThreadPerTaskExecutor(), submit stock.available và shipping.fee trên virtual thread, rồi chờ từng Future bằng await(task, deadline) với deadline = now + 2s. RestClient của shipping còn có readTimeout 2s từ TimeoutConfig.Java does the same in QuoteService.quote(orderId): it opens scope = Executors.newVirtualThreadPerTaskExecutor(), submits stock.available and shipping.fee on virtual threads, then waits on each Future with await(task, deadline) where deadline = now + 2s. The shipping RestClient also has a 2s readTimeout from TimeoutConfig.
7Quá hạn, get() ném TimeoutException; khối catch gọi cancel(true) cho cả qty lẫn fee nên subtask chưa xong bị interrupt. Rời khối try là scope.close(): executor chờ chúng thoát hẳn, không thread nào bị bỏ rơi.Past the deadline, get() throws TimeoutException; the catch block calls cancel(true) on both qty and fee, so unfinished subtasks are interrupted. Leaving the try block calls scope.close(): the executor waits for them, so no thread is orphaned.
8ReportExporter.exportWithLimit submit export(orderIds) lên ExecutorService (virtual thread). job.get(limit) hết giờ (production 30 giây, demo 300ms) thì job.cancel(true) chỉ bật cờ interrupt; vòng lặp export tự kiểm tra isInterrupted() rồi return.ReportExporter.exportWithLimit submits export(orderIds) to the ExecutorService (virtual threads). When job.get(limit) times out (30 seconds in production, 300ms in the demo), job.cancel(true) only sets the interrupt flag; the export loop checks isInterrupted() itself and returns.
9Go huỷ chủ động: Track tạo ctx bằng WithCancel và chạy go Poll, mỗi giây đẩy out <- loc. Màn hình đóng, caller gọi cancel(); Poll rơi vào nhánh <-ctx.Done(), ghi log rồi thoát, không rò goroutine.Go manual cancellation: Track creates ctx with WithCancel and runs go Poll, which pushes out <- loc every second. When the screen closes the caller calls cancel(); Poll hits the <-ctx.Done() case, logs and exits, so no goroutine leaks.