我正在创建一个将数据上传到服务器的应用程序。数据将相当庞大,高达60-70 60。我使用java,因为我需要它在任何浏览器中运行。
我的方法是这样:
InputStream s = new FileInputStream(file);
byte[] chunk = new byte[20000000];
s.read(chunk);
s.close();
client.postToServer(chunk);目前,它使用大量内存,稳定地上升到大约1gb,当垃圾收集器击中它时,很明显,块之间有5-6秒的间隔。
是否有任何方法来提高这方面的性能,并将内存占用保持在一个合理的水平?
编辑:
这不是我的真正密码。还有很多其他的事情我喜欢计算CRC,验证InputStream.read返回值,等等。
发布于 2011-03-14 13:56:23
您需要考虑缓冲区重用,如下所示:
int size = 64*1024; // 64KiB
byte[] chunk = new byte[size];
int read = -1;
for( read = s.read(chunk); read != -1; read = s.read(chunk)) {
/*
* I do hope you have some API call like the thing below, or at least one with a wrapper object that
* exposes partially filled buffers. Because read might not be the size of the entire buffer if there
* are less than that amount of bytes available in the input stream until the end of the file...
*/
client.postToServer(chunk, 0, read);
}发布于 2011-03-14 13:44:22
第一步是重复使用缓冲区,如果您还没有这样做的话。读取一个大文件应该是,而不是,通常需要大量内存,除非您将其全部保存在内存中。
还有:你为什么要使用这么大的缓冲区?它并没有什么真正的好处(除非你有一个疯狂快速的网络连接&硬盘)。将其降低到大约64k不会对性能产生负面影响,并且可能有助于Java使用GC。
发布于 2011-03-14 13:48:45
您可以尝试调优垃圾收集器( http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html,http://www.petefreitag.com/articles/gctuning/ )
https://stackoverflow.com/questions/5299335
复制相似问题