目录
正在加载目录…
正在阅读专栏 Java 专栏 第 8 篇 · 共 22 篇 · 36%

Java 8:函数式编程、Stream 与时间建模

发布于 2026-09-24 20:51 · 最后编辑于 2026-10-03 09:12 · 版本 v5 · 字数 5,498 · 预计阅读 11 分钟 👁 41 次阅读

Java 8 函数式与时间 API:从批处理管道到异步结算

Lambda、Stream、Optional、java.time 与 CompletableFuture 不是五组独立语法糖:它们分别约束行为、数据流、缺失、时间和异步失败;只有边界清楚,批处理代码才既简洁又可验证。

TL;DR

  • Lambda 必须落到函数式接口的目标类型;它只能捕获 final 或 effectively final 的局部变量。需要可变状态时,先问状态是否本应共享,而不是机械换成数组或原子类绕过编译器。
  • Stream 是一次性、惰性的计算描述。中间操作在终止操作到来前不会执行;并行执行仍要求非干扰、无状态和可结合的归约。
  • Optional 适合表达“查询结果可能不存在”。数据损坏、权限拒绝和基础设施失败不是正常缺失,不能统一变成 Optional.empty()。
  • LocalDate 表示日历日期,Instant 表示时间线事件,ZonedDateTime 表示带本地规则的时刻;DST 期间“加两小时”与“走到墙上时间两点后”不是同一语义。
  • CompletableFuture 必须显式定义执行器、超时、取消和异常归属。Java 8 没有 orTimeout;超时 future 完成不等于底层任务已经停止。

阅读契约

项目说明
读者起点能使用集合、异常和普通线程池,理解不可变数据的基本价值
前置知识Java 集合与泛型 的所有权/PECS,Java 异常与资源管理 的失败传播
读完能力能用无副作用 Stream 建模批处理,用正确时间类型表达业务事实,并为异步任务配置隔离与超时
后续主题Java 18-21 并发、模式与集合演进 的虚拟线程,Java 并发入门 的容量与取消

名词解释

名词含义本文中的作用
Target typeLambda 被赋值/传参时对应的函数式接口类型决定参数、返回值和可抛异常
Intermediate operation返回新 Stream 的惰性操作filter、map、peek
Terminal operation触发管道求值并消费 Streamcollect、reduce、anyMatch
Non-interference数据源在管道执行期间不被操作逻辑破坏并行和顺序 Stream 的正确性前提
Short-circuit无需检查全部输入即可得到结果anyMatch 找到首个高风险账单
Civil time由日历、时区和本地规则解释的时间截止日和营业时间
Timeline time全球时间线上的一个瞬间支付受理事件的 Instant
Completion stage异步计算及其后续组合节点税费与风险查询的 thenCombine

目录

章节说明
问题入口:批处理写短了,边界却丢了同一结算场景中的五类错误
完整批次:纯管道、缺失和时间模型可复制运行的主程序
Lambda捕获的不是魔法闭包目标类型与 effectively final
Stream为什么惰性且只能消费一次管道、融合和短路
并行Stream不能共享可变结果容器竞态与 collect 修复
Optional只表达正常缺失查询边界和错误边界
日期、时刻与时区必须分开建模LocalDate、Instant、ZonedDateTime
CompletableFuture需要资源与失败协议显式 executor、Java 8 超时与取消
架构师视角:函数式写法不取消系统约束容量、隔离、时间与观测
JUnit验证与示例工程文章测试和深入入口

问题入口:批处理写短了,边界却丢了

每日账单结算需要完成这些动作:筛选到期未支付账单、查询客户、计算总额、遇到高风险账单时尽早停止检查、记录受理时刻,并并行查询税费和风险结果。

如果只追求“链式写法”,常见错误包括:

写法隐藏假设可观察故障
在 parallelStream().forEach 中写共享 ArrayList多线程 add 自动安全丢元素、数组损坏或偶尔看似正确
把所有异常转换为 Optional.empty()缺失与失败等价数据损坏和基础设施故障被静默跳过
用 LocalDateTime 保存支付受理事件服务器默认时区永远不变跨区域排序、重放和审计不一致
依赖 common pool 做远程 I/O所有并行/异步任务可共享容量一个慢下游拖慢整个进程的公共任务
future 超时后认定远程调用已停止超时会强制取消底层 I/O任务继续占线程、连接并产生副作用

完整批次:纯管道、缺失和时间模型

下面的单文件程序把日历事实、时间线事件、客户缺失、短路检查和结算结果放在同一个模型中。它在 JDK 8 可直接运行。

java BillingBatchDemo.java
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public final class BillingBatchDemo {
    private BillingBatchDemo() {
    }

    public static void main(String[] args) {
        List<Invoice> invoices = sampleInvoices();
        CustomerDirectory directory = sampleDirectory();
        LocalDate businessDate = LocalDate.of(2026, 3, 20);
        Instant acceptedAt = Instant.parse("2026-03-20T09:00:00Z");

        BatchResult result = settle(
                invoices, directory, businessDate, acceptedAt);
        System.out.println("selected=" + result.invoiceIds());
        System.out.println("total=" + result.total);
        System.out.println(
                "risk=" + result.hasHighRisk
                        + ", visits=" + result.riskVisits
                        + "/" + invoices.size());
        System.out.println(
                "missing customer skipped="
                        + (result.settlements.size() == 2));
        System.out.println("acceptedAt=" + result.acceptedAt);

        ZoneId newYork = ZoneId.of("America/New_York");
        ZonedDateTime beforeDstJump = ZonedDateTime.of(
                LocalDate.of(2026, 3, 8),
                LocalTime.of(1, 30),
                newYork);
        ZonedDateTime afterTwoElapsedHours =
                beforeDstJump.plus(Duration.ofHours(2));
        System.out.println(
                "branch time after 2h=" + afterTwoElapsedHours);
    }

    static BatchResult settle(
            List<Invoice> invoices,
            CustomerDirectory directory,
            LocalDate businessDate,
            Instant acceptedAt) {
        AtomicInteger riskVisits = new AtomicInteger();
        boolean highRisk = invoices.stream()
                .peek(invoice -> riskVisits.incrementAndGet())
                .anyMatch(Invoice::isHighRisk);

        List<Settlement> settlements = invoices.stream()
                .filter(invoice -> !invoice.paid)
                .filter(invoice -> !invoice.dueDate.isAfter(businessDate))
                .map(invoice -> directory.find(invoice.customerId)
                        .map(customer -> new Settlement(
                                invoice.id,
                                customer.displayName(),
                                invoice.amount))
                        .orElse(null))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        BigDecimal total = settlements.stream()
                .map(settlement -> settlement.amount)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .setScale(2);

        return new BatchResult(
                settlements,
                total,
                highRisk,
                riskVisits.get(),
                acceptedAt);
    }

    static List<Invoice> sampleInvoices() {
        return Arrays.asList(
                new Invoice("inv-1", "c-1", "10.00",
                        LocalDate.of(2026, 3, 20), false, false),
                new Invoice("inv-2", "c-2", "20.00",
                        LocalDate.of(2026, 3, 19), false, true),
                new Invoice("inv-3", "c-1", "30.00",
                        LocalDate.of(2026, 3, 18), true, false),
                new Invoice("inv-4", "missing", "40.00",
                        LocalDate.of(2026, 3, 18), false, false));
    }

    static CustomerDirectory sampleDirectory() {
        Map<String, Customer> customers = new HashMap<String, Customer>();
        customers.put("c-1", new Customer("c-1", null, "Ada Lovelace"));
        customers.put("c-2", new Customer("c-2", "Grace", "Grace Hopper"));
        return new CustomerDirectory(customers);
    }

    static final class Invoice {
        final String id;
        final String customerId;
        final BigDecimal amount;
        final LocalDate dueDate;
        final boolean paid;
        final boolean highRisk;

        Invoice(
                String id,
                String customerId,
                String amount,
                LocalDate dueDate,
                boolean paid,
                boolean highRisk) {
            this.id = id;
            this.customerId = customerId;
            this.amount = new BigDecimal(amount);
            this.dueDate = dueDate;
            this.paid = paid;
            this.highRisk = highRisk;
        }

        boolean isHighRisk() {
            return highRisk;
        }
    }

    static final class Customer {
        final String id;
        final String nickname;
        final String legalName;

        Customer(String id, String nickname, String legalName) {
            this.id = id;
            this.nickname = nickname;
            this.legalName = legalName;
        }

        String displayName() {
            return Optional.ofNullable(nickname).orElse(legalName);
        }
    }

    static final class CustomerDirectory {
        private final Map<String, Customer> customers;

        CustomerDirectory(Map<String, Customer> customers) {
            this.customers = Collections.unmodifiableMap(
                    new HashMap<String, Customer>(customers));
        }

        Optional<Customer> find(String id) {
            return Optional.ofNullable(customers.get(id));
        }
    }

    static final class Settlement {
        final String invoiceId;
        final String customerName;
        final BigDecimal amount;

        Settlement(
                String invoiceId,
                String customerName,
                BigDecimal amount) {
            this.invoiceId = invoiceId;
            this.customerName = customerName;
            this.amount = amount;
        }
    }

    static final class BatchResult {
        final List<Settlement> settlements;
        final BigDecimal total;
        final boolean hasHighRisk;
        final int riskVisits;
        final Instant acceptedAt;

        BatchResult(
                List<Settlement> settlements,
                BigDecimal total,
                boolean hasHighRisk,
                int riskVisits,
                Instant acceptedAt) {
            this.settlements = Collections.unmodifiableList(
                    new ArrayList<Settlement>(settlements));
            this.total = total;
            this.hasHighRisk = hasHighRisk;
            this.riskVisits = riskVisits;
            this.acceptedAt = acceptedAt;
        }

        List<String> invoiceIds() {
            return settlements.stream()
                    .map(settlement -> settlement.invoiceId)
                    .collect(Collectors.toList());
        }
    }
}

固定 JDK 8 后执行:

bash
JDK8_HOME=$(/usr/libexec/java_home -v 1.8)
"$JDK8_HOME/bin/java" -version
"$JDK8_HOME/bin/javac" BillingBatchDemo.java
"$JDK8_HOME/bin/java" BillingBatchDemo

稳定输出:

text
selected=[inv-1, inv-2]
total=30.00
risk=true, visits=2/4
missing customer skipped=true
acceptedAt=2026-03-20T09:00:00Z
branch time after 2h=2026-03-08T04:30-04:00[America/New_York]

数据怎样穿过管道

mermaid
flowchart LR
    I[Invoice列表] --> F[筛选到期且未支付]
    F --> O[Optional查询客户]
    O --> S[生成Settlement]
    S --> C[collect为结果列表]
    C --> R[reduce汇总金额]
    I --> A[anyMatch短路风险检查]

批次主路径不在 Stream stage 内调用远程系统。CustomerDirectory 是已加载的本地快照;真实远程税费/风险查询放到后面的显式异步边界,避免把阻塞 I/O 隐藏进 map。

Lambda捕获的不是魔法闭包

Lambda 在编译期必须有目标函数式接口,目标类型决定参数、返回值和可抛异常。局部变量只能在 final 或 effectively final 状态下被捕获:

java
int count = 0;
// Runnable broken = () -> count++; // 编译错误

如果允许捕获后修改普通栈局部变量,Lambda 的生命周期可能超过方法栈帧,语义和线程安全都不清楚。把变量换成单元素数组虽然能绕过检查,却把共享可变状态藏进闭包。

BillingBatchDemo 的 AtomicInteger 只用于观察短路访问次数;业务结果不依赖它。若计数本身是业务状态,应显式建模所有权和并发语义,而不是在 Stream 中用副作用累加。

常见函数式接口:

接口输入输出常见用途
Predicate<T>Tbooleanfilter、匹配规则
Function<T,R>TRmap、模型转换
Consumer<T>T无边界输出;不适合作为纯管道状态容器
Supplier<T>无T延迟创建、异步任务
BinaryOperator<T>T,TT可结合归约

Stream为什么惰性且只能消费一次

filter、map、peek 等中间操作只构造管道。终止操作到来时,Stream 才从源拉取元素,并可能把多层操作融合到一次遍历。短路终止操作在结果确定后停止请求元素。

本文 anyMatch 的第二个账单即为高风险,所以访问次数为 2,而不是列表总数 4。这个结果依赖 encounter order 和当前顺序 Stream;若换成无序/并行管道,不应把具体访问次数当业务契约。

Stream 只能执行一次。终止后再次使用会抛 IllegalStateException。它代表一次计算,不是可以长期持有和重复查询的数据集合;需要重复计算时应从集合重新创建 Stream,或把结果物化为集合。

peek不是业务副作用钩子

peek 主要服务调试和观察。短路、优化或不同执行模式会改变它被调用的元素数量;把数据库写入、计费或消息发送放进 peek 会让副作用次数依赖求值策略。本文只用它统计教学访问次数,并通过测试锁定当前顺序场景。

reduce要求结合律

并行归约会分块计算再合并。累加器/组合器必须满足身份元素和结合性。减法不满足结合律:

text
(10 - 3) - 2 != 10 - (3 - 2)

顺序结果与某次并行观察不同,不是 Stream 错误,而是调用方违反归约契约。不要把某台机器观察到的具体错误数字写成并行 Stream 的保证。

并行Stream不能共享可变结果容器

下面程序刻意展示错误与修复。错误版本把多个 worker 的结果写入普通 ArrayList;它可能丢元素、抛异常,也可能某次恰好正确。程序只打印不变量,不承诺固定错误数字。

java ParallelCollectionFailure.java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public final class ParallelCollectionFailure {
    private ParallelCollectionFailure() {
    }

    public static void main(String[] args) {
        int expected = 20_000;
        List<Integer> shared = new ArrayList<Integer>();
        RuntimeException failure = null;
        try {
            IntStream.range(0, expected)
                    .parallel()
                    .forEach(shared::add);
        } catch (RuntimeException observed) {
            failure = observed;
        }

        long distinct = -1L;
        try {
            distinct = shared.stream().distinct().count();
        } catch (RuntimeException observationFailure) {
            if (failure == null) {
                failure = observationFailure;
            }
        }
        boolean invariantBroken =
                failure != null
                        || shared.size() != expected
                        || distinct != expected;
        System.out.println(
                "wrong expected=" + expected
                        + ", actual=" + shared.size()
                        + ", distinct=" + distinct
                        + ", raceObserved=" + invariantBroken);

        List<Integer> repaired = IntStream.range(0, expected)
                .parallel()
                .boxed()
                .collect(Collectors.toList());
        System.out.println(
                "repaired expected=" + expected
                        + ", actual=" + repaired.size()
                        + ", distinct="
                        + repaired.stream().distinct().count());
    }

    static List<Integer> collectSafely(int count) {
        return IntStream.range(0, count)
                .parallel()
                .boxed()
                .collect(Collectors.toList());
    }
}
bash
JDK8_HOME=$(/usr/libexec/java_home -v 1.8)
"$JDK8_HOME/bin/javac" ParallelCollectionFailure.java
"$JDK8_HOME/bin/java" ParallelCollectionFailure

稳定的是修复行:actual=20000, distinct=20000。错误行的 actual、distinct 和 raceObserved 允许每次不同;若一次显示 raceObserved=false,只能说明该次调度未观察到破坏,不能证明代码安全。

collect(toList()) 让 Stream 框架为各分区维护局部容器,再按 collector 规则合并。它不是把同一个 ArrayList 暴露给所有 worker。

Optional只表达正常缺失

CustomerDirectory.find 返回 Optional<Customer>,因为“客户 ID 在本次目录快照中不存在”是调用方必须处理的查询结果。调用方明确选择跳过账单。

这些情况不应变成 empty:

  • 目录文件损坏;
  • 调用方无权读取客户;
  • 数据库/网络超时;
  • 客户记录违反必填字段约束;
  • 程序缺陷导致空指针。

它们需要不同异常或结果分类,否则批次会把系统故障误报为“没有客户”。Optional 也不适合做实体字段、集合元素和方法参数的默认包装;这些位置通常可以用明确字段约束、空集合或重载表达。

orElse 会先求值默认表达式,即使 Optional 有值;昂贵或有副作用的默认值使用 orElseGet。本文 legal name 已经存在于对象中,因此 orElse(legalName) 没有额外副作用。

日期、时刻与时区必须分开建模

业务事实类型原因
发票截止日LocalDate只关心日历日期,不代表全球瞬间
支付受理事件Instant可跨区域排序、审计和重放
纽约分行营业规则ZoneId/ZonedDateTime本地偏移和 DST 是事实的一部分
经过 2 小时Duration时间线上的固定秒数
经过 2 个日历月Period日历单位,不是固定秒数

纽约在 2026-03-08 从 02:00 跳到 03:00。01:30-05:00 加两小时 elapsed duration 得到 04:30-04:00。墙上时间跨了三小时,时间线只经过两小时。若业务要求“当地 03:30 执行”,应按本地规则解析下一次时刻,而不是简单加固定 Duration。

不要使用服务器默认时区做业务决策。默认时区会随容器镜像、启动参数或部署区域变化。把 ZoneId 作为配置/领域输入,并在持久化时同时保存可重放所需的信息。

测试当前时间时注入 Clock:生产用 Clock.systemUTC(),测试用 Clock.fixed(...)。这比在断言中容忍几秒误差更确定。

CompletableFuture需要资源与失败协议

下面程序使用独立的有界 worker pool 和单线程 timeout scheduler。成功路径组合税费与风险;超时路径使用 Java 8 的 anyOf,不调用 Java 9+ 的 orTimeout。

java AsyncSettlement.java
import java.math.BigDecimal;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

public final class AsyncSettlement {
    private AsyncSettlement() {
    }

    public static void main(String[] args) throws Exception {
        ExecutorService workers = newWorkers();
        ScheduledExecutorService timer =
                java.util.concurrent.Executors
                        .newSingleThreadScheduledExecutor(
                                namedFactory("settlement-timeout-"));
        CountDownLatch releaseSlowTask = new CountDownLatch(1);
        try {
            CompletableFuture<String> success = combineQuotes(workers);
            System.out.println("async success=" + success.join());

            CompletableFuture<String> slow = CompletableFuture.supplyAsync(
                    () -> {
                        try {
                            releaseSlowTask.await();
                            return "late";
                        } catch (InterruptedException interrupted) {
                            Thread.currentThread().interrupt();
                            throw new CompletionException(interrupted);
                        }
                    },
                    workers);
            try {
                withTimeout(slow, 20L, timer).join();
            } catch (CompletionException failure) {
                Throwable cause = rootCause(failure);
                System.out.println(
                        "async failure="
                                + cause.getClass().getSimpleName()
                                + ": "
                                + cause.getMessage());
            }
        } finally {
            releaseSlowTask.countDown();
            workers.shutdownNow();
            timer.shutdownNow();
            workers.awaitTermination(1, TimeUnit.SECONDS);
            timer.awaitTermination(1, TimeUnit.SECONDS);
        }
    }

    static CompletableFuture<String> combineQuotes(
            ExecutorService workers) {
        CompletableFuture<BigDecimal> tax =
                CompletableFuture.supplyAsync(
                        () -> new BigDecimal("2.00"), workers);
        CompletableFuture<String> risk =
                CompletableFuture.supplyAsync(() -> "LOW", workers);
        return tax.thenCombine(
                risk,
                (taxValue, riskValue) ->
                        "tax=" + taxValue + ",risk=" + riskValue);
    }

    static <T> CompletableFuture<T> withTimeout(
            CompletableFuture<T> source,
            long timeoutMillis,
            ScheduledExecutorService timer) {
        final CompletableFuture<T> timeout =
                new CompletableFuture<T>();
        final ScheduledFuture<?> scheduled = timer.schedule(
                () -> timeout.completeExceptionally(
                        new TimeoutException(
                                "settlement timeout after "
                                        + timeoutMillis + " ms")),
                timeoutMillis,
                TimeUnit.MILLISECONDS);
        source.whenComplete((value, failure) -> scheduled.cancel(false));

        CompletableFuture<Object> first =
                CompletableFuture.anyOf(source, timeout);
        return first.thenApply(new Function<Object, T>() {
            @SuppressWarnings("unchecked")
            @Override
            public T apply(Object value) {
                return (T) value;
            }
        });
    }

    static Throwable rootCause(Throwable failure) {
        Throwable current = failure;
        while (current instanceof CompletionException
                && current.getCause() != null) {
            current = current.getCause();
        }
        return current;
    }

    static ExecutorService newWorkers() {
        return new ThreadPoolExecutor(
                2,
                2,
                0L,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(4),
                namedFactory("settlement-worker-"),
                new ThreadPoolExecutor.AbortPolicy());
    }

    static ThreadFactory namedFactory(final String prefix) {
        return new ThreadFactory() {
            private final AtomicInteger sequence = new AtomicInteger();

            @Override
            public Thread newThread(Runnable task) {
                Thread thread = new Thread(
                        task, prefix + sequence.incrementAndGet());
                thread.setDaemon(true);
                return thread;
            }
        };
    }
}
bash
JDK8_HOME=$(/usr/libexec/java_home -v 1.8)
"$JDK8_HOME/bin/javac" AsyncSettlement.java
"$JDK8_HOME/bin/java" AsyncSettlement

预期稳定输出:

text
async success=tax=2.00,risk=LOW
async failure=TimeoutException: settlement timeout after 20 ms

withTimeout 只让返回给调用方的 stage 超时。底层 slow 任务仍可能运行,因此 finally 中释放 latch 并关闭 executor。真实远程调用还要把截止时间传到 HTTP/数据库客户端,并定义取消后副作用是否可能已经发生。

为什么不使用默认执行器

无参数 supplyAsync/runAsync 通常使用 ForkJoinPool.commonPool()。parallel Stream 也默认使用共享设施。把慢 I/O、CPU 批处理和框架内部任务混在一起,会让一个工作负载挤占另一个工作负载,且无法独立设置队列、线程名、拒绝和指标。

本文的 worker pool 有固定线程数和有界队列。AbortPolicy 让过载显式失败;生产边界应把拒绝映射为稳定错误/指标,而不是悄悄换成无界队列。

架构师视角:函数式写法不取消系统约束

1. 管道只承载内存计算

Stream 适合有界、内存内、可组合的转换。远程 I/O 需要超时、重试、限流、连接池和隔离;把它藏进 map 会让一条看似纯函数的管道包含不可见故障面。

2. 并行之前先证明三个条件

  • stage 无共享可变状态;
  • reduce/collector 满足并行契约;
  • 数据规模和单元素计算足以覆盖拆分/合并成本。

然后用实际负载测量。parallel() 不是性能注解,也不是背压机制。

3. 时间字段必须写出语义

数据库列名和 API 字段应区分 dueDate、acceptedAt、branchZone 等语义,而不是都叫 time。跨时区审计保存 Instant;重现本地规则还需保存 ZoneId 或规则版本。

4. 异步容量来自下游而不是CPU数量

线程、队列和并发请求数要受连接池、下游 QPS、延迟 SLO 和超时预算约束。超时只停止等待,不自动撤销副作用;需要请求 ID、幂等和客户端取消协议。

5. 失败只转换一次

CompletionException 是组合容器。应用边界先恢复根因,再按稳定分类映射;中间 stage 不应每层记录并包装,否则调用方无法判断超时、拒绝、业务失败和程序缺陷。

JUnit验证与示例工程

文章内测试

java Java8BillingTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;

public class Java8BillingTest {
    @Test
    public void batchUsesShortCircuitOptionalAndExactMoney() {
        BillingBatchDemo.BatchResult result = BillingBatchDemo.settle(
                BillingBatchDemo.sampleInvoices(),
                BillingBatchDemo.sampleDirectory(),
                LocalDate.of(2026, 3, 20),
                Instant.parse("2026-03-20T09:00:00Z"));

        assertEquals(Arrays.asList("inv-1", "inv-2"),
                result.invoiceIds());
        assertEquals(new BigDecimal("30.00"), result.total);
        assertTrue(result.hasHighRisk);
        assertEquals(2, result.riskVisits);
    }

    @Test
    public void repairedParallelCollectionPreservesAllElements() {
        List<Integer> values =
                ParallelCollectionFailure.collectSafely(10_000);
        assertEquals(10_000, values.size());
        assertEquals(10_000, values.stream().distinct().count());
    }

    @Test
    public void explicitExecutorCombinesAsyncResults() throws Exception {
        ExecutorService workers = AsyncSettlement.newWorkers();
        try {
            assertEquals(
                    "tax=2.00,risk=LOW",
                    AsyncSettlement.combineQuotes(workers)
                            .get(1, TimeUnit.SECONDS));
        } finally {
            workers.shutdownNow();
        }
    }

    @Test
    public void java8TimeoutCompletesExceptionally() throws Exception {
        ScheduledExecutorService timer =
                Executors.newSingleThreadScheduledExecutor();
        try {
            CompletableFuture<String> never =
                    new CompletableFuture<String>();
            try {
                AsyncSettlement.withTimeout(never, 10L, timer).join();
            } catch (CompletionException failure) {
                assertTrue(
                        AsyncSettlement.rootCause(failure)
                                instanceof TimeoutException);
                return;
            }
            throw new AssertionError("expected timeout");
        } finally {
            timer.shutdownNow();
        }
    }
}

文件放置为三个主类位于 src/main/java/,测试位于 src/test/java/。最小 POM 使用 Java 8/JUnit 4.13.1:

xml pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>example</groupId>
    <artifactId>java8-billing</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
bash
JAVA_HOME=$(/usr/libexec/java_home -v 1.8) mvn test

预期结果:

text
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
BUILD SUCCESS

示例工程

exercises-java-core/java8-features 包含 Lambda 捕获编译失败、Stream 惰性、非结合归约、Optional 和 DST 的 8 条测试。执行时必须记录实际 runtime;旧缓存报告来自 JDK 25,不等于 JDK 8 运行证据:

bash
JAVA_HOME=$(/usr/libexec/java_home -v 1.8) \
  mvn -pl java8-features test -Dsort.skip=true

正文已经独立提供批次、并行集合和异步超时完整代码;工程用于更细的语言机制实验。

相关笔记

参考资料

← 返回列表
← 上一篇 Java 类加载:类型身份、委派与初始化 下一篇 → Java 9 模块系统:可读性、导出与服务加载
(2 人打了分,平均分: 5.00)

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论