我们在服务器程序中经常用到日志,日志对于我们排查问题有很大的帮助。
下面是日志服务的思路以及实现
思路:多个生产者单个消费者的设计方式,每个调用log的操作都相当于一个生产者,而后台的日志线程则相当于消费者。
public class LoggerService {
private final BlockingQueue<String> queue;
private final LoggerThread loggerThread;
private final PrintWriter writer;
private boolean isShutdown;
private int reservations;
public LoggerService(Writer writer) {
this.queue = new LinkedBlockingQueue<>();
this.loggerThread = new LoggerThread();
this.writer = new PrintWriter(writer);
}
public void start() {
loggerThread.start();
}
public void stop() {
synchronized (this) {
isShutdown = true;
}
loggerThread.interrupt();
}
public void log(String msg) throws InterruptedException {
synchronized (this) {
if (isShutdown) {
throw new IllegalStateException();
}
++reservations;
}
queue.put(msg);
}
private class LoggerThread extends Thread {
@Override
public void run() {
while (true) {
try {
synchronized (LoggerService.this) {
if (isShutdown && reservations == 0) {
break;
}
}
String msg = queue.take();
synchronized (LoggerService.this) {
--reservations;
}
writer.println(msg);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
writer.close();;
}
}
}
}
}