Switch to full style
General Java code examples
Post a reply

Asynchronous Logger using Java

Wed Feb 06, 2013 11:23 pm

Asynchronous Logger using Java with threading.
java code
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);
}




Post a reply
  Related Posts  to : Asynchronous Logger using Java
 Java extending org.apache.log4j.Logger     -  
 How asynchronous is AJAX     -  
 GUI logger     -  
 2d game in java-Monster-Java 2D Game Graphics and Animation     -  
 need help in java     -  
 What is Java API?!!!     -  
 java or .net     -  
 what is java     -  
 Using FTP in java     -  
 Java course     -  

Topic Tags

Java Files and I/O