我为我的程序编写了一个后台日志记录线程,如果一个类需要一个记录器,它会从我的线程池中提取它,因此对于每个文件名,只有一个日志正在运行。该类添加了需要通过 log(String) 记录的任何内容。
无论如何,每当我设置登录并在一段时间后运行 writetolog() 时,我都会遇到 heapoutofmemory 异常。这是由日志线程引起的,但是我看不到内存泄漏在哪里,而且我不擅长线程。我唯一的想法是它在缓冲的作家中?
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<String> pq = new LinkedBlockingQueue<String>();
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();}
}
}
编辑 - 值得一提的是,在程序的上下文中,它记录了 100 到 1000 行
非常感谢山姆