M4RKYU.SYSEdition 2027
Skip to content
LOCZH/安大略 · 加拿大/▸logs · understanding final finally and finalize in java 3p0h待机OK/--:--:--EST
M4M4RK_YUportfolio
  • 创作创作
    创作Overview
    • 作品精选案例与项目记录
    • 游戏可玩原型与游戏开发日志
  • 影像影像
    影像Overview
    • 照片影像合集与视觉实验
    • 商店印刷品、海报和限量物件
  • 写作写作
    写作Overview
    • 博客长篇开发日志与现场笔记
    • 笔记短观察、链接与代码片段
  • 资源资源
    资源Overview
    • 工具38 款浏览器内开发工具
    • 链接每日使用的开发与设计书签
  • 关于关于
  • 联系联系
EN

同步 · dev.to / @markyu

Java final, finally, finalize: Three Bugs They Prevent

A practical Java explanation of final, finally, and finalize using real failure modes instead of memorized definitions.

发布日期
May 24 '24
·
阅读时长
2 min read
·
点赞
13
·
评论数
3
javabackendprogrammingbeginners
在 dev.to 查看评论

本页目录

  • Quick Map
  • final: Stop Accidental Change
  • finally: Cleanup Even When Things Break
  • finalize: Know It, Then Avoid It
  • The Rule I Use
  • Final Thought

final, finally, and finalize look like siblings.

They are not.

I have seen beginners mix them up because tutorials explain them as definitions. I think they make more sense if you connect each one to the bug it prevents.

Quick Map

Keyword / methodWhat it protects against
finalaccidental reassignment, override, or inheritance
finallycleanup code being skipped
finalizemostly historical cleanup confusion

The uncomfortable truth: you should understand finalize, but you probably should not use it.

final: Stop Accidental Change

Use final when a value or behavior should not be changed after it is set.

public class RateLimiter {
    private final int maxRequests;

    public RateLimiter(int maxRequests) {
        this.maxRequests = maxRequests;
    }

    public boolean allow(int currentRequests) {
        return currentRequests < maxRequests;
    }
}

Here maxRequests cannot be reassigned after construction. That is boring, and boring is good.

You can also use final on methods:

class BaseService {
    public final void audit() {
        System.out.println("audit event written");
    }
}

A subclass cannot override audit(). I would use this sparingly. If you need final everywhere, your inheritance design may already be too clever.

And on classes:

public final class StringUtils {
    private StringUtils() {}
}

This says: do not extend this class.

finally: Cleanup Even When Things Break

finally runs whether the try block succeeds or throws.

Old-style file handling:

FileReader reader = null;

try {
    reader = new FileReader("config.txt");
    // read file
} catch (IOException e) {
    System.out.println("read failed: " + e.getMessage());
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException ignored) {
            // logging would be better in production
        }
    }
}

This works, but modern Java gives you a cleaner option:

try (FileReader reader = new FileReader("config.txt")) {
    // read file
} catch (IOException e) {
    System.out.println("read failed: " + e.getMessage());
}

That is try-with-resources. In most production code, I would prefer it over a manual finally.

Still, finally matters when cleanup is not an AutoCloseable resource:

lock.lock();
try {
    updateSharedState();
} finally {
    lock.unlock();
}

This is the real bug finally prevents: a lock stays locked because an exception jumped over your cleanup line.

finalize: Know It, Then Avoid It

finalize() was intended to run before garbage collection reclaims an object.

@Override
protected void finalize() throws Throwable {
    System.out.println("cleanup before GC");
}

Do not build production cleanup around this.

Why?

  • You do not control when GC runs.
  • It may run much later than expected.
  • It adds performance and reliability problems.
  • It has been deprecated for removal in modern Java.

If you need cleanup, use AutoCloseable:

class ConnectionHandle implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("connection closed");
    }
}

try (ConnectionHandle handle = new ConnectionHandle()) {
    System.out.println("using connection");
}

This is explicit. You can reason about it. Production code likes that.

The Rule I Use

  • Use final to make intent harder to accidentally break.
  • Use finally when cleanup must happen even after exceptions.
  • Avoid finalize; use explicit cleanup instead.

Final Thought

These three names are confusing, but the responsibilities are not.

final is about preventing change. finally is about guaranteed cleanup. finalize is a legacy GC hook you should not lean on.

Which Java keyword confused you the most when you first learned backend development?

相关阅读

Java throw vs throws: The Exception Bug They Reveal

A practical Java exception handling guide explaining throw, throws, checked exceptions, runtime exceptions, and API boundary decisions.

java

Java BeanUtils Copying: Convenient, but Not Free

A practical Java guide to BeanUtils, shallow copy pitfalls, reflection overhead, and when MapStruct or manual mapping is a better choice.

java

Frontend Linear Data Structures Deep Dive: Arrays, Stacks, Queues, and Linked Lists

The Big Picture Before diving into stacks, queues, and linked lists, it helps to know...

computerscience

原文发布

本文首发于 dev.to,评论与点赞保留在原站。

在 dev.to 继续阅读
上一篇Java throw vs throws: The Exception Bug They RevealA practical Java exception handling guide explaining throw, throws, checked exceptions, runtime exceptions, and API boundary decisions.
返回全部文章
下一篇Database Table Design Starts With the Queries You NeedA practical database table design guide focused on queries, keys, indexes, normalization, constraints, and production tradeoffs.
返回档案
M4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYU
始于 2024
ZhenXiao Mark YuZhenXiao Mark Yu
联系

看到什么有意思的?和我聊聊。

这是一个作品集,不是服务 · 但每一条留言我都会看 — 如果哪里让你有所触动,或者只想打个招呼,欢迎写信过来。

开启对话
频道开放

随时打个招呼 · 2026

--:--:--EST加拿大 安大略
  • 邮件
  • GitHub
  • dev.to
  • 领英
  • 推特 / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat

订阅

偶尔收到一封简讯

来自 m4rkyu.com 的笔记与日志——简短、标注日期、没有杂音。随时可退订。

作品

线上发布、游戏作品与视觉档案。

  • 项目
  • 游戏
  • 档案
  • 日志

资源

每日好用的工具与个人收藏的链接库。

  • 搜索
  • 最新
  • 工具
  • 链接
  • 笔记
  • 主题
  • 商店
RSSJSON Feed

工作室

背景、联系方式以及合作渠道。

  • 关于
  • 联系
  • 更新日志
  • 技术说明
  • 简历筹备中

社交

在常去的平台上找到我。

  • GitHub
  • dev.to
  • 领英
  • 推特 / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
  • 邮件
© 2026 ZhenXiao Mark Yumarkyu0615@gmail.com
  • 邮件
  • GitHub
  • dev.to
  • 领英
  • 推特 / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
隐私条款由 Next.js 16 · React 19 · Tailwind 4 构建