取消、中断与资源释放
→ 返回工程实践路线
四种完成不是一回事
取消请求已发出、Future 被标记取消、工作线程退出、业务副作用完成或撤销,是不同事件。调用方不再等待,不代表后台任务已经停止,也不代表连接、许可和外部资源已归还。
Future.cancel(true) 尝试取消并可能中断执行线程,实际行为还要看实现。特别是 CompletableFuture 的取消不承诺中断底层计算,不能把 Future 接口的全部实现都按同一种执行模型理解。Future API
中断是协作机制
线程可以检查中断状态;部分阻塞方法通过 InterruptedException 响应。纯计算长期不检查状态、库忽略信号或某些 IO 路径,都可能使停止延后。
处理中断时,按方法契约向上抛出,或在不能抛出的边界恢复中断状态并结束当前工作。不能记录日志后继续无限循环,也不应使用强制终止线程来模拟安全回滚。
可运行示例(Java 17)
保存为 CancellationCleanupDemo.java,编译运行:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class CancellationCleanupDemo {
public static void main(String[] args) throws Exception {
CountDownLatch started = new CountDownLatch(1);
CountDownLatch cleaned = new CountDownLatch(1);
AtomicBoolean closed = new AtomicBoolean();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<?> task = executor.submit(() -> {
try (AutoCloseable resource = () -> closed.set(true)) {
started.countDown();
new CountDownLatch(1).await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
cleaned.countDown();
}
});
if (!started.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("task did not start");
}
System.out.println(task.cancel(true));
if (!cleaned.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("cleanup not observed");
}
System.out.println(closed.get());
} finally {
executor.shutdownNow();
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("executor still running");
}
}
}
}正常完成时输出两个 true。显式清理门闩证明资源关闭阶段已发生,不把取消返回值当作资源释放证明。示例使用可响应中断的等待,不代表任意库调用都同样可取消。
资源生命周期要可追踪
文件、流、连接租借、锁、信号量许可和临时文件需要明确所有者。取得成功后,使用 finally 或 try-with-resources 等确保归还;获取失败时不要误释放不属于自己的资源。
取消前已经提交的数据不因线程退出而自动回滚。外部操作结果未知时,按稳定操作标识查询与恢复,不要把“任务 cancelled”直接映射成“业务未发生”。
执行器关闭语义
shutdown 停止接收新任务并允许已提交工作推进;shutdownNow 尝试停止执行并返回部分未开始任务,不保证所有任务立刻结束。等待终止需要明确预算与超时后的恢复处理。ExecutorService