当前位置:网站首页>面试官:JVM如何分配和回收堆外内存
面试官:JVM如何分配和回收堆外内存
2022-07-03 16:04:00 【InfoQ】
JVM内存模型

如何分配堆外内存
第一种方式:ByteBuffer#allocateDirect
//分配10M的内存
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(10 * 1024 * 1024);
第二种方式:Unsafe#allocateMemory
public class Test {
private static Unsafe unsafe = null;
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
//分配10M的内存
Field getUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
getUnsafe.setAccessible(true);
unsafe = (Unsafe)getUnsafe.get(null);
//分配完内存返回内存的地址
long address = unsafe.allocateMemory(10 * 1024 * 1024);
}
}
如何回收堆外内存
第一种方式:Unsafe#freeMemory
public class Test {
private static Unsafe unsafe = null;
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
//分配10M的内存
Field getUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
getUnsafe.setAccessible(true);
unsafe = (Unsafe)getUnsafe.get(null);
//分配完内存返回内存的地址
long address = unsafe.allocateMemory(10 * 1024 * 1024);
//回收分配的堆外内存
unsafe.freeMemory(address);
}
}
第二种方式:JVM回收堆外内存

- JVM执行Full GC时会将DirectByteBuffer进行回收,回收之后Clearner就不存在引用关系
- 再下一次发生GC时会将Cleaner对象放入ReferenceQueue中,同时将Cleaner从链表中移除
- 最后调用unsafe#freeMemory清除堆外内存
注意点
注意点1:
注意点2:
边栏推荐
- Uploads labs range (with source code analysis) (under update)
- SDNU_ ACM_ ICPC_ 2022_ Winter_ Practice_ 4th [individual]
- Pandora IOT development board learning (HAL Library) - Experiment 5 external interrupt experiment (learning notes)
- CString在多线程中的问题
- do{}while()的妙用
- App移动端测试【5】文件的写入、读取
- Unity功能——Unity离线文档下载及使用
- Rk3399 platform development series explanation (WiFi) 5.54. What is WiFi wireless LAN
- 用同花顺炒股开户安全吗?
- [proteus simulation] 74hc595+74ls154 drive display 16x16 dot matrix
猜你喜欢
Microservice API gateway zuul
Asemi rectifier bridge umb10f parameters, umb10f specifications, umb10f package
From the 18th line to the first line, the new story of the network security industry
初试scikit-learn库
Detailed pointer advanced 1
App移动端测试【3】ADB命令
Rk3399 platform development series explanation (WiFi) 5.54. What is WiFi wireless LAN
Microservice API gateway
【Proteus仿真】8×8LED点阵屏仿电梯数字滚动显示
请做好3年内随时失业的准备?
随机推荐
半监督学习
Vs2017 is driven by IP debugging (dual machine debugging)
Create gradle project
Jmeter线程组功能介绍
近视:摘镜or配镜?这些问题必须先了解清楚
Wechat payment -jsapi: code implementation (payment asynchronous callback, Chinese parameter solution)
"Everyday Mathematics" serial 56: February 25
Is it safe to open an account with tongdaxin?
Semi supervised learning
Microservice API gateway zuul
六月 致 -.-- -..- -
《微服务设计》读书笔记(下)
Uploads labs range (with source code analysis) (under update)
Secsha system 1- login function
Qt插件之自定义插件构建和使用
App mobile terminal test [3] ADB command
Mb10m-asemi rectifier bridge mb10m
WinDbg analysis dump file
Chinese translation of Tagore's floating birds (1~10)
Function introduction of JMeter thread group