您好我使用以下代码使用sun.misc.Unsafe存储字符串:
package com.util.OffHeapStorage;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class OffHeapStorage {
static Unsafe unsafe = getUnsafe();
static Unsafe getUnsafe() {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe) f.get(null);
} catch (Exception x) {
x.printStackTrace();
}
return null;
}
static long storeString(String str){
long bytes = 2;
long startAddress = unsafe.allocateMemory(bytes);
int strlength = str.length();
for(long i=0;i<strlength;i++){
char ch = str.charAt((int)i);
unsafe.putChar(startAddress + i*2, ch);
System.out.println("Stored "+ch+" to address "+(startAddress+i*2));
}
return startAddress;
}
static String fetchString(long startAddress, int strlength){
StringBuilder strOut = new StringBuilder();
for(long i = startAddress; i < startAddress + strlength * 2; i += 2 ){
strOut.append(unsafe.getChar(i));
}
return strOut.toString();
}
static void freeStringMemory(long startAddress, int strlength ){
for(long i = startAddress; i < startAddress + strlength * 2; i += 2 ){
unsafe.freeMemory(i);
}
}
public static void main(String [] args){
String message = "Hello World";
long stringAddress = storeString(message);
System.out.println(fetchString(stringAddress, message.length()));
//freeStringMemory(stringAddress, message.length());
}
}
正如你所看到的,我没有释放记忆。
此代码的输出将告诉我存储的字符串的起始地址,我想检查是否可以在另一个类中使用以获取字符串值。
所以我的另一堂课看起来像:
public static void main(String [] args){
String message = "Hello World";
long stringAddress = 413100824;
System.out.println(fetchString(stringAddress, message.length()));
freeStringMemory(stringAddress, message.length());
}
然而,在执行此类时,我收到此错误:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6ce8d1b3, pid=11624, tid=0x000025c0
#
# JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
# Java VM: Java HotSpot(TM) Client VM (25.131-b11 mixed mode windows-x86 )
# Problematic frame:
# V [jvm.dll+0x13d1b3]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:\localeclipseworkspace\OffHeapStorage\hs_err_pid11624.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
#
我刚试过Java Unsafe,也许我的整个概念都错了。本质上,我试图检查是否可以将数据存储在操作系统内存中,而不是增加我的JVM负担。
非常感谢任何帮助。