Note that there are some explanatory texts on larger screens.

plurals
  1. POLog thread memory leak
    text
    copied!<p>I have coded a background logging thread for my program, if a class needs a logger it pulls it from my threadpool, so for each filename there is only one log running. The class, adds anything which needs to be logged via log(String). </p> <p>Anyway whenever I set logging on and it runs the writetolog() after a while I get heapoutofmemory exception. This is caused by the log threads, but I can't see where the memory leak is, and I am not that great at threading. My only idea is that it is in the buffered writer?</p> <pre><code>import java.io.File; import java.io.IOException; import java.io.FileWriter; import java.util.Calendar; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class Log extends Thread{ private String file; private BlockingQueue&lt;String&gt; pq = new LinkedBlockingQueue&lt;String&gt;(); private BufferedWriter bw; private boolean Writing; @Depreciated public Log(){ super(); file = "log.txt"; start(); } public Log(ThreadGroup tg, String fileName){ super(tg,fileName); file = fileName; try { new File(file).createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } start(); } public Log(String fileName){ file = fileName; try { new File(file).createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } start(); } @Override public void run(){ //System.out.println("Log Thread booted " +file); while(Run.running){ if (!Writing){ if(Run.logging) writeToLog(); } try{ Thread.sleep(500); }catch(InterruptedException e){ Thread.currentThread().interrupt(); break; } } //System.out.println("Log Thread shutting down " +file); } public synchronized void log(String s){ if(Run.logging) pq.add(s); } private void writeToLog(){ try{ Writing = true; bw = new BufferedWriter(new FileWriter(file, true)); while(!pq.isEmpty()){ bw.write(Calendar.getInstance().getTime().toString() +" " +pq.poll()); bw.newLine(); } bw.flush(); bw.close(); Writing = false; }catch(Exception e){Writing = false; e.printStackTrace();} } } </code></pre> <p>EDIT - It is worth mentioning as well that in the context of the program it is logging 100's - 1000's of lines </p> <p>Many thanks Sam</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload