考虑以下方法:Java中的多线程垃圾回收:外部共享对象阻止GC?
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)的内存消耗,我可以慢慢但肯定地看到内存消失。我很感激你能给我的任何建议。