Consider the following method:
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();
}
where S is a large array (hundreds of thousands) and O is of say length 50. My question is regarding the RO object. It is created outside and "shared" if you will by all the threads. Now when this code has run for some time the heap space runs out which has puzzled me. I am inclined to think that the RO object still keeps the otherwise completed Runnables alive and slowly eat up the memory. Is that true? I have monitored the memory consumption of the linux system (latest version of Oracle JDK) using `free -m' and I can slowly but surely see the memory disappear. I am thankful for any advice you can give me.