java - 在 main() 中设置系统资源限制时,Java JNA 应用程序崩溃
问题描述
我有一个 JNA 应用程序需要计算大型一维数组 (~1G) 中的元素总和。使用 JNA Resource.Rlimit 类,我可以增加资源限制,如以下代码段所示:
final Resource.Rlimit limit = new Resource.Rlimit();
limit.rlim_cur = 1024L * 1024L * 1024L;
limit.rlim_max = 2 * 1024L * 1024L * 1024L;
但是,这只适用于在分配大数组的方法中设置堆栈大小的情况。因此,当我运行以下代码时,没有内存不足异常。
package com.jnaapps;
import com.sun.jna.Library;
import com.sun.jna.Pointer;
import com.sun.jna.Native;
import com.sun.jna.Memory;
import com.sun.jna.platform.unix.LibCAPI;
import com.sun.jna.platform.unix.Resource;
public class Main {
public interface CLibrary extends LibCAPI, Library {
CLibrary INSTANCE = (CLibrary) Native.load("c", CLibrary.class);
}
public interface NativeClass extends Library {
NativeClass INSTANCE = (NativeClass)Native.load("nativemethods", NativeClass.class);
double sumOfArray1d(final Pointer values, long numberOfValues);
}
public static void main(String[] args) {
Test0();
}
public static void Test0() {
final Resource.Rlimit limit = new Resource.Rlimit();
limit.rlim_cur = 1024L * 1024L * 1024L;
limit.rlim_max = 2 * 1024L * 1024L * 1024L;
int err = CLibrary.INSTANCE.setrlimit(Resource.RLIMIT_STACK, limit);
if (err != 0) {
int lastError = Native.getLastError();
System.out.println("An exception occurred while setting RLimit: " +
lastError);
}
NativeClass clib = NativeClass.INSTANCE;
long dim = 10000L * 10000L;
final Pointer bigVector = new Memory(dim*Native.getNativeSize(Double.TYPE));
for (long i=0; i<dim; ++i) {
bigVector.setDouble(i*Native.getNativeSize(Double.TYPE), 3.5e-6);
}
double total = clib.sumOfArray1d(bigVector, dim);
System.out.println("Sum of elements in big vector = " + total);
}
public static void Test1() {
NativeClass clib = NativeClass.INSTANCE;
long dim = 10000L * 10000L;
final Pointer bigVector = new Memory(dim*Native.getNativeSize(Double.TYPE));
for (long i=0; i<dim; ++i) {
bigVector.setDouble(i*Native.getNativeSize(Double.TYPE), 3.5e-6);
}
double total = clib.sumOfArray1d(bigVector, dim);
System.out.println("Sum of elements in big vector = " + total);
}
}
但是,当在 main() 中设置资源限制并调用方法 Test1() 时,程序会崩溃。
public static void main(String[] args) {
final Resource.Rlimit limit = new Resource.Rlimit();
limit.rlim_cur = 1024L * 1024L * 1024L;
limit.rlim_max = 2 * 1024L * 1024L * 1024L;
int err = CLibrary.INSTANCE.setrlimit(Resource.RLIMIT_STACK, limit);
if (err != 0) {
int lastError = Native.getLastError();
System.out.println("An exception occurred while setting RLimit: " +
lastError);
}
Test1();
}
为什么我不能在调用 Test1() 之前增加 main() 中的堆栈大小。该项目是在具有 8GB RAM 的 Ubuntu 16.04 amdx86-64 上使用 IntelliJ Idea(社区版本 2019.3)编写的。
解决方案
推荐阅读
- php - WP查询评论数
- reactjs - 私有路由重定向到 404 错误页面而不是登录页面
- javascript - 如何打印具有数组的对象具有属性?反应原生
- c++ - 分配 C++ 指针
- mysql - 使用 Node.JS 和 MYSQL 删除数据库记录时出错
- xml - 为什么编辑休眠映射xml没有可见的类?
- typescript - 由于找不到 ts-node-dev,在 elasticbeanstalk 上运行 typescript 应用程序的问题
- ios - 为 UIViewPropertyAnimator 的 fractionComplete 设置大于 1 或小于 0 的值
- reactjs - 提交表单调用 API Next.js
- html - HTML 音频无法在移动设备上播放