我正在尝试从文件(运行 10 分钟的 10 个线程)中读取大量数据(10k-20k 记录)。我得到一个例外:
Exception in thread "main" Exception in thread "Thread-26" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Unknown Source)
at java.lang.String.<init>(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
我收到以下代码片段的上述错误消息。我一直在尝试调试这个:我最接近的是使用 CharSequence。但我仍然得到堆异常。(此时 - 谁能帮我理解为什么 CharSequence 会更好?=> 似乎它会在主内存中加载少量数据,但最终所有数据都需要在主内存中)。
如果 1 分钟,我可以运行代码。但是任何接近 10 分钟的东西都会爆炸。有没有一种有效的方法来读取文件?
**此代码是研究的一部分,我仍在重构它,因此确实存在许多低效代码。
try{
for(int i=0; i<threadCount; i++){
fstream = new FileInputStream(dir+"//read"+machineid+"-"+i + ".txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
// Read File Line By Line
String[] tokens;
while ((line = br.readLine()) != null) {
tokens = line.split(",");
logObject record = new logObject(tokens[0], tokens[1], tokens[2],tokens[3], tokens[4], tokens[5], tokens[6], tokens[7], "", tokens[8]);
toBeProcessed[toBeProcessedArraySz] = record;
toBeProcessedArraySz++;
if(readToValidate == toBeProcessedArraySz){
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace(System.out);
}
//create thread to process the read records
ValidationThread newVThread = new ValidationThread(props,toBeProcessed, updateStats, initCnt, semaphore, finalResults, staleSeqSemaphore, staleSeqTracker, seqTracker, seenSeqSemaphore, toBeProcessedArraySz, freshnessBuckets,bucketDuration);
vThreads.add(newVThread);
toBeProcessedArraySz = 0;
toBeProcessed = new logObject[readToValidate];
semaphore.release();
newVThread.start();
}
}
br.close();//remove to test
fstream.close();
}
}catch(Exception e){
e.printStackTrace(System.out);
}