【发布时间】:2012-07-04 06:48:14
【问题描述】:
我已经使用两个数组构建了一个自定义哈希图。一个包含键另一个值。现在,我看到有时 JVM 无法为这些数组分配所需的内存并抛出异常。有什么方法可以使用页面交换或任何其他方法来解决这个问题?
代码:
public class Test1{
public static void main(String args[]){
try {
int arrays[] = new int[50000000] ;
for ( int i = 0; i < 50000000 ; i++)
{
arrays[i] = i ;
}
}
catch(Exception e){
System.out.println(e) ;
}
}
}
编辑:
public void load() {
try {
FileChannel channel2 = new RandomAccessFile(str1, "r").getChannel();
MappedByteBuffer mbb2 = channel2.map(FileChannel.MapMode.READ_ONLY, 0, channel2.size());
mbb2.order(ByteOrder.nativeOrder());
assert mbb2.remaining() == savenum * 8;
for (int i = 0; i < savenum; i++) {
long l = mbb2.getLong();
keys[i] = l;
}
channel2.close();
FileChannel channel3 = new RandomAccessFile(str2, "r").getChannel();
MappedByteBuffer mbb3 = channel3.map(FileChannel.MapMode.READ_ONLY, 0, channel3.size());
mbb3.order(ByteOrder.nativeOrder());
assert mbb3.remaining() == savenum * 4;
for (int i = 0; i < savenum; i++) {
int l1 = mbb3.getInt();
values[i] = l1;
}
channel3.close();
} catch (Exception e) {
System.out.println(e);
}
}
public void save() {
try {
FileChannel channel = new RandomAccessFile(str1, "rw").getChannel();
MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_WRITE, 0, savenum * 8);
mbb.order(ByteOrder.nativeOrder());
for (int i = 0; i < savenum; i++) {
mbb.putLong(keys[i]);
}
channel.close();
FileChannel channel1 = new RandomAccessFile(str2, "rw").getChannel();
MappedByteBuffer mbb1 = channel1.map(FileChannel.MapMode.READ_WRITE, 0, savenum * 4);
mbb1.order(ByteOrder.nativeOrder());
for (int i = 0; i < savenum; i++) {
mbb1.putInt(values[i]);
}
channel1.close();
} catch (Exception e) {
System.out.println("IOException : " + e);
}
}
【问题讨论】:
-
尝试用更多的堆空间启动 JVM?
-
你考虑过 SQL 数据库吗?
-
页面交换是操作系统所做的事情。首先确保您没有任何实际的内存泄漏。 (作为第一步,使用最大堆大小分析应用程序的内存使用情况,并检查它是否在某个时候稳定。)
-
@Tudor,一直这样做是有问题的。
-
@Arpssss 为什么会有问题?您不能期望每个应用程序都使用默认设置。除此之外,启动脚本中的一个开关?
标签: java