加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

OSX上的Java文件限制低于bash

发布时间:2020-12-15 05:00:38 所属栏目:Java 来源:网络整理
导读:我已经增加了我的macbook pro上的最大文件限制,以便Elasticsearch可以处理更多文件,但它无法正常工作. 我运行命令’ulimit -a’,它说“打开文件”是100,000.我可以像这样运行一个简单的shell脚本: export counter=0while (true) ; do touch "/tmp/foo${coun
我已经增加了我的macbook pro上的最大文件限制,以便Elasticsearch可以处理更多文件,但它无法正常工作.

我运行命令’ulimit -a’,它说“打开文件”是100,000.我可以像这样运行一个简单的shell脚本:

export counter=0
while (true) ; do touch "/tmp/foo${counter}" ; export counter=`expr $counter + 1` ; done

而且我能够创建大量文件(在我杀死脚本之前超过60,000个).

但是,使用Java代码在“/ tmp”目录的空子目录中创建RandomAccessFiles,在出现错误之前,我只能生成10,232个文件:java.io.FileNotFoundException(打开的文件太多).这是我的Java代码:

import java.io.*;
import java.util.*;

public class max_open_files {
    public static void main(String ... args) throws Exception {
        File testDir = new File("/tmp/tempsubdir");
        testDir.mkdirs();

        List<File> files = new LinkedList<File>();
        List<RandomAccessFile> fileHandles = new LinkedList<RandomAccessFile>();

        try {
            while (true) {
                File f = new File(testDir,"tmp" + fileHandles.size());
                RandomAccessFile raf = new RandomAccessFile(f,"rw");
                files.add(f);
                fileHandles.add(raf);
            }
        } catch (Exception ex) {
            System.out.println(ex.getClass() + " " + ex.getMessage());
        }

        for (RandomAccessFile raf : fileHandles) raf.close()

        for (File f : files) f.delete();

        System.out.println("max open files: " + fileHandles.size());
    }
}

此java代码类似于Elasticsearch中的代码,用于测试文件数量的限制(在maxOpenFiles方法的FileSystemUtils类中).所以Elasticsearch与我的Java程序有同样的问题.

为什么shell脚本可以生成比Java代码(我和Elasticsearch)更多的文件?为什么Java系统无法识别高系统对文件数量的限制?

5月13日下午4:50更新CDT:我创建了一个测试程序的C版本,以查看限制是否特定于Java,看起来是这样.下面的C版本可以打开32,765个文件,而Java代码限制为10,232个文件.

#include <stdio.h>
#include <stdlib.h>

int main(int argc,const char *argv) {
    char name[100];
    FILE *fp;
    int ndx;

    for (ndx = 0; ndx < 50000; ndx++) {
        sprintf(name,"/tmp/foo%d.txt",ndx);
        fp = fopen(name,"w");
        if (fp == NULL) {
            fprintf(stdout,"Can not create file %dn",ndx);
            return 1;
        }
        fprintf(fp,"hello %d",ndx);
    }

    return 0;
}

解决方法

Java Virtual Machine Option Reference for Mac

-XX:- MaxFDLimit

Directs the VM to refrain from setting the file descriptor limit to the default maximum. The default behavior is to set the limit to the value specified by OPEN_MAX,which is 10240. Normally,this is the maximum number of files that a process may have open. It is possible,however,to increase this limit to a user-specified value with the sysctl utility. Under such circumstances,you may want to pass -XX:-MaxFDLimit to stop the Java VM from restricting the number of open files to 10240.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读