# 引用类型

对象的引用和判定对象是否存活有着很重要的关系。在 JDK 1.2 之前，Java 中引用的定义很传统：如果 reference 类型的数据中存储的数值代表的是另一块内存的起始地址，就成该 reference 数据是代表某块内存、某个对象的引用。在这种定义下，对象的引用只有「被引用」和「未被引用」两种状态。

在 JDK 1.2 之后，Java 对引用的概念进行了扩充，将引用分为 **强引用**（Strong Reference）、**软引用**（Soft Reference）、**弱引用**（Weak Reference）、**虚引用**（Phantom Reference）：

* 强引用是最传统的「引用」定义，是指在程序代码中普遍存在的引用赋值。无论在任何情况下，只要强引用关系还存在，垃圾收集器就永远 **不会回收被引用的对象**；
* 软引用是用来描述一些还有用但非必须的对象。被软引用关联的对象，**会在即将发生 OOM 之前被回收**。在 JDK 中使用 `SoftReference` 来实现软引用；
* 弱引用也是用来描述一些非必须的对象，但是它的强度比软引用更弱一些。被弱引用关联的对象，**会在下一次发生 GC 时被回收**。在 JDK 中使用 `WeakReference` 来实现弱引用；
* 虚引用是最弱的一种引用关系，并且与对象是否存活无关。设置虚引用的唯一目的是为了在对象被 GC 时，垃圾收集器能接收到一个系统通知。

## 案例

* `ThreadLocal.ThreadLocalMap` 使用弱引用来存储数据；
* `com.google.common.cache.LocalCache` 支持使用软引用和弱引用的缓存失效策略。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.fantasticmao.cn/tech/java/jvm/yin-yong-lei-xing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
