Wed Feb 06, 2013 11:23 pm
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.io.PrintStream;
public class LogAsynchronous implements Logger {
private List logData = Collections.synchronizedList(new ArrayList());
private Thread threadLogger;
private boolean running = false;
private int logged = 0;
private PrintStream logStream;
public LogAsynchronous(PrintStream stream) {
logStream = stream;
running = true;
threadLogger = new Thread(new LoggerThread());
threadLogger.setPriority(Thread.NORM_PRIORITY - 3);
threadLogger.start();
}
private void mainLoggerLoop() {
while (running) {
logQueuedMessages();
sleepTillMoreMessagesQueued();
}
}
private void logQueuedMessages() {
while (messagesInQueue() > 0)
logOneMessage();
}
private void logOneMessage() {
String msg;
msg = (String) logData.remove(0);
logStream.println(msg);
logged++;
}
private void sleepTillMoreMessagesQueued() {
try {
synchronized (logData) {
logData.wait();
}
} catch (InterruptedException e) {
}
}
public void logMessage(String msg) {
logData.add(msg);
wakeLoggerThread();
}
public int messagesInQueue() {
return logData.size();
}
public int messagesLogged() {
return logged;
}
public void stop() throws InterruptedException {
running = false;
wakeLoggerThread();
threadLogger.join();
}
private void wakeLoggerThread() {
synchronized (logData) {
logData.notifyAll();
}
}
private class LoggerThread implements Runnable {
public void run() {
mainLoggerLoop();
}
}
}
interface Logger {
public void logMessage(String message);
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.