Reputation: 69259
I've got a question, because I am going to develop a simple yet very specialized logging system, other logging systems currently do not fit my needs.
The code:
package customlogger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author student
*/
public class CustomLogger implements Runnable {
private BlockingQueue<String> queue;
private List<LogConsumer> consumers;
public CustomLogger() {
this.queue = new LinkedBlockingQueue<>();
this.consumers = new ArrayList<>();
}
@Override
public void run() {
while (true) {
try {
String message = queue.take();
for (LogConsumer consumer : consumers) {
consumer.consume(message);
}
} catch (InterruptedException ex) {
Logger.getLogger(CustomLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void log(String message) {
queue.offer(message);
}
public void addConsumer(LogConsumer consumer) {
if (consumers.contains(consumer)) {
return;
}
consumers.add(consumer);
}
public void removeConsumer(LogConsumer consumer) {
if (!consumers.contains(consumer)) {
return;
}
consumers.remove(consumer);
}
}
package customlogger;
/**
*
* @author student
*/
public interface LogConsumer {
public void consume(String message);
}
package customlogger;
/**
*
* @author student
*/
public class SystemOutConsumer implements LogConsumer {
@Override
public void consume(String message) {
System.out.println(message);
}
}
Creation code:
LogConsumer systemOutConsumer = new SystemOutConsumer();
CustomLogger simpleLogger = new CustomLogger();
simpleLogger.addConsumer(systemOutConsumer);
Thread simpleLoggerThread = new Thread(simpleLogger);
simpleLoggerThread.start();
Now assume I want to log a lot of messages with simpleLogger.log(message);
, will this harm the performance of my program itself?
I run the CustomLogger
in its own thread so that should not (directly) impact the performance of my program, but is this also the case for the System.out.println(message)
that is done by the logger?
Upvotes: 0
Views: 86
Reputation: 1131
It will not affect performance of your main thread if you do it like this. But I would reconsider using existing logging framework since I don't see that you created anything that's not possible to do with log4j for example ... ...
Upvotes: 1