Total members 11894 |It is currently Sat Nov 23, 2024 3:38 am Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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);
}




_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 1 post ] 

  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     -  
 Java course     -  
 need help in java     -  
 What is Java API?!!!     -  
 java or .net     -  
 what is java     -  
 Using FTP in java     -  



Topic Tags

Java Files and I/O






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
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