# java.lang.OutOfMemoryError：直接缓冲区内存

- **ID:** `java/outofmemoryerror-direct-buffer-memory`
- **领域:** java
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

JVM 已耗尽直接字节缓冲区的堆外内存限制（MaxDirectMemorySize），通常由分配大量直接 ByteBuffer 而不释放，或 NIO 操作泄漏直接内存引起。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Java 8 | active | — | — |
| Java 11 | active | — | — |
| Java 17 | active | — | — |
| Java 21 | active | — | — |

## 解决方案

1. ```
   Ensure direct ByteBuffers are explicitly released after use by calling the cleaner or using try-with-resources if possible. For Netty or other NIO frameworks, check for buffer pooling and leak detection.
   ```
2. ```
   Increase the MaxDirectMemorySize JVM parameter to accommodate legitimate direct memory usage, but also implement proper cleanup.
   ```
3. ```
   Use a memory-mapped file or heap-based ByteBuffer instead of direct ByteBuffer when possible, to avoid off-heap memory pressure.
   ```

## 无效尝试

- **** — Increasing heap space (-Xmx) does not affect direct memory limits; direct memory is separate from heap. (95% 失败率)
- **** — Enabling GC logging without tuning direct memory does not prevent the leak; it only helps diagnose. (90% 失败率)
- **** — Setting MaxDirectMemorySize to a very high value only delays the crash; the underlying leak continues. (70% 失败率)
