直接看這里https://zhuanlan.zhihu.com/p/268822452
簡介
NativeAllocationRegistry 是 Android 平臺中的一個類,它用于管理在 Java 和 Native 代碼間的內(nèi)存分配。
當(dāng)java對象被回收后, 通過某種機(jī)制回調(diào)之前注冊的native層的內(nèi)存回收函數(shù). 這里說的機(jī)制具體是指引用隊(duì)列.
它通過注冊內(nèi)存分配方法和內(nèi)存釋放方法,來管理在 Java 和 Native 代碼間的內(nèi)存分配和釋放。這樣,Java 應(yīng)用程序可以通過調(diào)用 NativeAllocationRegistry 的方法分配內(nèi)存,而在不再使用該內(nèi)存時,NativeAllocationRegistry 將自動釋放這些內(nèi)存。
這樣,使用 NativeAllocationRegistry 可以幫助開發(fā)人員避免內(nèi)存泄漏和其他內(nèi)存問題,同時也提高了代碼的可讀性和可維護(hù)性。
因此,如果你在開發(fā) Android 平臺的 Native 應(yīng)用程序,并需要在 Java 和 Native 代碼間分配內(nèi)存,那么你可以考慮使用 NativeAllocationRegistry 來管理內(nèi)存分配和釋放。
原理
NativeAllocationRegistry 的實(shí)現(xiàn)原理基于 Java 和 Native 代碼間的內(nèi)存分配。
在 Java 代碼中,NativeAllocationRegistry 定義了一組內(nèi)存分配方法和內(nèi)存釋放方法。當(dāng) Java 代碼需要分配內(nèi)存時,它會調(diào)用 NativeAllocationRegistry 的內(nèi)存分配方法,進(jìn)而分配內(nèi)存。
在 Native 代碼中,NativeAllocationRegistry 會調(diào)用相應(yīng)的內(nèi)存釋放方法,釋放分配的內(nèi)存。
通過這種方式,NativeAllocationRegistry 可以管理 Java 和 Native 代碼間的內(nèi)存分配和釋放,避免內(nèi)存泄漏和其他內(nèi)存問題,同時也提高了代碼的可讀性和可維護(hù)性。
因此,NativeAllocationRegistry 的實(shí)現(xiàn)原理是通過定義內(nèi)存分配方法和內(nèi)存釋放方法,管理 Java 和 Native 代碼間的內(nèi)存分配和釋放。
使用
- 創(chuàng)建 NativeAllocationRegistry 實(shí)例:
NativeAllocationRegistry registry = new NativeAllocationRegistry(
ClassLoader.getSystemClassLoader(),
new NativeAllocationRegistry.Sizes(
sizeOfNativeObject,
sizeOfNativeContext,
sizeOfNativeAllocation),
numberOfNativeAllocations);
- 定義內(nèi)存分配方法:
long allocateNative(int size) {
return registry.newNonNativeAllocation(size, 0);
}
- 定義內(nèi)存釋放方法:
void freeNative(long address) {
registry.free(address);
}
- 在 Java 代碼中調(diào)用內(nèi)存分配方法:
long nativeAddress = allocateNative(size);
- 在 Native 代碼中調(diào)用內(nèi)存釋放方法:
freeNative(nativeAddress);