考虑以下方法:
public void Parse(String[] S, Objects[] O) throws IOException {
final int N_THREADS = Runtime.getRuntime().availableProcessors();
BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(20);
RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
ThreadPoolExecutor service = new ThreadPoolExecutor(N_THREADS, N_THREADS, 0L, TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler);
final SomeObject RO = new SomeObject();
for(String s : S){
service.execute(new Runnable() {
public void run() {
// initialize variables
for (Object o : O) {
V ps = RO.apply(sentence);
//more work on ps
}
File f = new File("something");
FileWriter fw = null;
try {
fw = new FileWriter(f.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
} catch (IOException e) {
System.out.println(f.getAbsoluteFile());
}
BufferedWriter bw = new BufferedWriter(fw);
for (SentenceAnnotation entry : annotations) {
try {
bw.write(entry.toString());
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
bw.flush();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
service.shutdown();
while (!service.isTerminated()) {
}
long timeEnd = System.currentTimeMillis();
}
其中 S 是一个大数组(数十万),O 的长度为 50。我的问题是关于 RO 对象。如果您愿意,它是在外部创建并由所有线程“共享”的。现在,当这段代码运行一段时间后,堆空间耗尽,这让我感到困惑。我倾向于认为 RO 对象仍然使原本已完成的 Runnables 保持活力并慢慢消耗内存。真的吗?我已经使用“free -m”监控了 linux 系统(最新版本的 Oracle JDK)的内存消耗,我可以缓慢但肯定地看到内存消失。我很感谢你能给我的任何建议。